views:

573

answers:

2

Hi,

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?

+8  A: 
$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:

Ionuț G. Stan
Damnit! Beat me by 18 seconds...
Matthew Scharley
Ah tanks, that easy. :-DOne more question, is there a way to test if that class really exist?Like:if( classExists( "MyClass")) { $obj = getInstanceOf( "MyClass");}
NovumCoder
There's `class_exists()`: http://www.php.net/manual/en/function.class-exists.php. Watch for the second argument though.
Ionuț G. Stan
Thank you guys. ReflectionClass is the perfect solution. Well i forgot that this is called Reflection not invoking. :-)
NovumCoder
+4  A: 

If the number of arguments needed by the constructor is known and constant, you can (as others have suggested) do this:

$className = 'MyClass';
$obj = new $className($arg1, $arg2, etc.); 
$obj->attribute = "Hello World";

As an alternative you could use Reflection. This also means you can provide an array of constructor arguments if you don't know how many you will need.

<?php
$rf = new ReflectionClass('MyClass');
$obj = $rf->newInstanceArgs($arrayOfArguments);
$obj->attribute = "Hello World";
Tom Haigh