开发者

How to "invoke" a class instance in PHP?

is there any possibility to "invoke" a class instance by a 开发者_StackOverflow社区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?


$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:

  • Object instantiation
  • ReflectionClass::newInstanceArgs()
  • ReflectionClass::newInstance()


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);


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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜