开发者

PHP passing a class as a reference?

开发者 https://www.devze.com 2023-03-09 15:44 出处:网络
in Python, you could do something like this: class SomeClass(object): pass s = SomeClass s开发者_如何学PythonomeClassInstance = s()

in Python, you could do something like this:

class SomeClass(object): pass
s = SomeClass
s开发者_如何学PythonomeClassInstance = s()

How could you accomplish the same effect in PHP? From what I understand, you cannot do this? Is this true?


You can create instances of dynamic class names; simply pass the name of the class as a string:

class SomeClass {}
$s = 'SomeClass';
$someClassInstance = new $s();


Using reflection:

class SomeClass {}
$s = new ReflectionClass('SomeClass');
$someClassInstance = $s->newInstance();

The nice thing about using reflection is that it throws a catchable exception in the event the class does not exist.

0

精彩评论

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