php - Accessing a specific instance of a class -


im pretty new oop php, , i'm trying learn.

i have class called "awesome_car" define so

class awesome_car {      public $attributes;     public $name;      function __construct($name, $atts) {         $this->name = $name;         $this->attributes = $atts;     }  } // end of class 

and instantiate class x times somewhere in code:

$car1 = new awesome_car('ford', array( 'color'=>'blue', 'seats' => 6 )); $car2 = new awesome_car('bmw', array( 'color'=>'green', 'seats' => 5 )); 

now make normal function allows me - , manipulate - specific instance of class name. like

function get_specific_car_instance($name) {      //some code retrives specific instance name      //do stuff instance      //return instance } 

i have seen people storing each instance in global variable array of object, i've read global variables considered bad practice? , find them bit annoying work well.

what better way of doing this? preferably oop approach?

if creating instances dynamically, storing them in array accepted way. doesn't have global however.

$cars = array();  $cars['ford'] = new awesome_car('ford', array( 'color'=>'blue', 'seats' => 6 )); $cars['bmw']  = new awesome_car('bmw', array( 'color'=>'green', 'seats' => 5 ));  $ford = $cars['ford']; 

this ofcourse can abstracted function such as:

function get_car(&$cars, $name) {     if (! isset($cars[$name])) {         throw new \invalidargumentexception('car not found');     }      return $cars[$name]; }  $ford = get_car($cars, 'ford'); 

or more advanced container classes such as:

// requires doctrine/common use doctrine\common\collections\arraycollection;  $cars = new arraycollection();  $cars->set('ford', new awesome_car('ford', array( 'color'=>'blue', 'seats' => 6 ))); $cars->set('bmw',  new awesome_car('bmw', array( 'color'=>'green', 'seats' => 5 )));  $ford = $cars->get('ford'); 

how store them later use depends quite bit on how dynamically creating them though.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -