9

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?

NovumCoder
  • 4,349
  • 9
  • 43
  • 58

3 Answers3

26
$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
  • 176,118
  • 18
  • 189
  • 202
  • Ah tanks, that easy. :-D One more question, is there a way to test if that class really exist? Like: if( classExists( "MyClass")) { $obj = getInstanceOf( "MyClass"); } – NovumCoder Oct 09 '09 at 09:18
  • There's `class_exists()`: http://www.php.net/manual/en/function.class-exists.php. Watch for the second argument though. – Ionuț G. Stan Oct 09 '09 at 09:21
  • Thank you guys. ReflectionClass is the perfect solution. Well i forgot that this is called Reflection not invoking. :-) – NovumCoder Oct 09 '09 at 09:36
  • newInstanceArgs function made my day. The last piece to finish my dependency resolver, so thank you! :) – Binke Mar 14 '14 at 19:50
14

The other answers will work in PHP <= 5.5, but this task gets a lot easier in PHP 5.6 where you don't even have to use reflection. Just do:

<?php

class MyClass
{
    public function __construct($var1, $var2)
    {}
}

$class = "MyClass";
$args = ['someValue', 'someOtherValue'];

// Here's the magic
$instance = new $class(...$args);
Lars Nyström
  • 5,786
  • 3
  • 32
  • 33
  • This answer needs more upvotes. Had no idea the "splat" operator even existed until today! http://php.net/manual/en/migration56.new-features.php#migration56.new-features.splat – Andy Feb 12 '17 at 17:14
6

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
  • 57,217
  • 21
  • 114
  • 142