vendredi 6 février 2015

Assigning child classes to a variable in parent class


Vote count:

0




I have these related classes:



class cars {

public $cars;

public function addCar($name, $car)
{
$this->cars[$name] = $car;
}

public function getCars()
{
return $this->cars;
}

public function getCar($name)
{
return $this->cars[$name];
}

public function getParams()
{
return $this->params;
}
}

$cars = new cars();

class bmw extends cars {

private static $_instance = null;
protected $params;

function __construct()
{
$this->params['param'] = 'foo';
}

public static function init()
{
if (self::$_instance === null) {
self::$_instance = new self;
}

return self::$_instance;
}
}

$cars->addCar( 'bmw', bmw::init() );


Basically i need to access all child classes from parent class. And use methods defined in parent class on those defined child classes. Parent class should not be modified when adding new child classes.


In the end this should work like this:



foreach( $cars->getCars() as $car )
{
foreach( $car->getParams() as $key => $param )
echo "$key = $param";
}


What is the proper way to do this?



asked 52 secs ago







Assigning child classes to a variable in parent class

Aucun commentaire:

Enregistrer un commentaire