How to "invoke" a class instance in PHP?

NovumCoder picture NovumCoder · Oct 9, 2009 · Viewed 16.9k times · Source

is there any possibility to "invoke" a class instance by a string representation?

In this case i would expect code to look like this:

class MyClass {
  public $attribute;
}

$obj = getInstanceOf( "MyClass"); //$obj is now an instance of MyClass
$obj->attribute = "Hello World";

I think this must be possible, as PHP's SoapClient accepts a list of classMappings which is used to map a WSDL element to a PHP Class. But how is the SoapClient "invoking" the class instances?

Answer

Ionuț G. Stan picture Ionuț G. Stan · Oct 9, 2009
$class = 'MyClass';
$instance = new $class;

However, if your class' constructor accepts a variable number of arguments, and you hold those arguments in an array (sort of call_user_func_array), you have to use reflection:

$class = new ReflectionClass('MyClass');
$args  = array('foo', 'bar');
$instance = $class->newInstanceArgs($args);

There is also ReflectionClass::newInstance, but it does the same thing as the first option above.

Reference: