如何“调用” PHP中的类实例? [英] How to "invoke" a class instance in PHP?
问题描述
有可能通过字符串表示调用类实例吗?
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";
我认为这是可能的,因为PHP的SoapClient接受一个classMappings的列表, WSDL元素到PHP类。但是如何SoapClient调用类实例?
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;
但是,如果你的类的构造函数接受可变数量的参数,数组( call_user_func_array
),您必须使用反射:
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);
还有 ReflectionClass :: newInstance
但它的作用与上述第一个选项相同。
There is also ReflectionClass::newInstance
, but it does the same thing as the first option above.
参考:
- Object instantiation
- ReflectionClass::newInstanceArgs()
- ReflectionClass::newInstance()
这篇关于如何“调用” PHP中的类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!