You can do this with Reflection:
<?php
class Pants
{
public function __construct($a, $b, $c)
{
$this->a = $a;
$this->b = $b;
$this->c = $c;
}
}
$className = 'pants';
$class = new ReflectionClass($className);
$obj = $class->newInstanceArgs(array(1, 2, 3));
var_dump($obj);
This will also work if your constructor uses the old style (unless your code makes use of namespaces and you are using PHP 5.3.3 or, presumably, greater, as old-style constructors will no longer work with namespaced code - more info):
<?php
class Pants {
function Pants($a, $b, $c) { ... }
}
If the class has no constructor and you wish to use reflection, use $class->newInstance()
instead of $class->newInstanceArgs(...)
. To do this dynamically, it would look like this:
$object = null === $class->getConstructor()
? $class->newInstance()
: $class->newInstanceArgs($args)
;