how to retrieve an array in this OOP case? [php] -


while know how solve in procedural php, i'm having difficulites oop. lines of code shortened (e.g. html).

so, user enters number, object $army1 passes constructor while creating itself. constructor fills array loop ($filled_army), don't know how retrieve right way (so print out after), since constructors don't have return values? adding print_r($filled_army); in constructor print out values, mention.

also, if problems shouldn't solved through __construct, can me how through own methods within class? i'm guessing should done getters & setters, had problems using them, since 1 variable passed in index.php, while other variable ($filled_army), property of class...

index.php

<form>   <input type="number" name="size"> </form>  <?php     $army1 = new army($_get['size']);     // $army1->getarmy(); ?? ?> 

army.class.php

<?php class army {   public $filled_army = [];   public size;   //...   public function __construct($size){         $this->size = $size;         $arrayofsoldiers = [10,20,30];          for($i=0; $i<$size; $i++)         {             $filled_army[$i] = $arrayofsoldiers[mt_rand(0, count($arrayofsoldiers) - 1)];         }     } } ?> 

since have declared $filled_army property public, available right after instantiating using standard object notation in php, example:

$army1 = new army($_get['size']); $army1->filled_army; // contains array; 

however, setting property's visibility public means code can modify property, not object created by. usually, work around set properties either protected or private, , use getters/setters:

class army {   private $filled_army = [];   private $army_size   = 0;    private static $_soldiers = [ 10, 20, 30 ];    function __construct($size)   {     $this->army_size = $size;      for($i = 0; $i < $size; $i++)     {       $this->filled_army[] = self::$_soldiers[ mt_rand(0, count(self::$_soldiers) - 1) ];     }   }     // getter army:   public function getarmy()   {     return $this->filled_army;   }    // getter size:   public function getarmysize()   {     return $this->army_size;   } } 

now, can access getarmy() method (or getarmysize() method):

$army1 = new army($_get['size']); $army1->getarmy();     // returns army $army1->getarmysize(); // returns value of $_get['size']; 

it's worth noting php supports magic getters/setters may useful project.

also note not need visibility modifier constructor function (__construct() in php always publicly visible).


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -