简体   繁体   English

PHP 通过 class 作为参考?

[英]PHP passing a class as a reference?

in Python, you could do something like this:在 Python 中,您可以执行以下操作:

class SomeClass(object): pass
s = SomeClass
someClassInstance = s()

How could you accomplish the same effect in PHP?您如何在 PHP 中实现相同的效果? From what I understand, you cannot do this?据我了解,您不能这样做吗? Is this true?这是真的?

You can create instances of dynamic class names;您可以创建动态 class 名称的实例; simply pass the name of the class as a string:只需将 class 的名称作为字符串传递:

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.使用反射的好处是,如果 class 不存在,它会抛出一个可捕获的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM