Dynamic Class Instantiation with Variable Parameter Count
Posted: Sun Sep 24, 2006 1:43 pm
I want to create a function that can create an instance of any class with any number of parameters.
This code gives me Fatal error: Non-static method Box::__construct() cannot be called statically. Any idea how I do this?
Otherwise, it'll be eval I guess.
Please don't post guesses without trying them first.
Thanks.
This code gives me Fatal error: Non-static method Box::__construct() cannot be called statically. Any idea how I do this?
Code: Select all
class Object
{
protected $_area;
public function getArea()
{
return $_area;
}
}
class Box extends Object
{
public function __construct($x, $y, $z)
{
$this->_area = $x * $y * $z;
}
}
class Square extends Object
{
public function __construct($x, $y)
{
$this->_area = $x * $y;
}
}
function createClass($name, $constructionParams)
{
return call_user_func_array(array($name, '__construct'), $constructionParams);
}
$a = createClass('Box', array(1, 2, 3));
echo $a->getArea();
$b = createClass('Square', array(4, 6));
echo $b->getArea();Please don't post guesses without trying them first.
Thanks.