有没有办法从类中获取静态属性而无需创建类的实例?
$reflection = new ReflectionObject( 'Foo' );
$staticProperties = $reflection->getStaticProperties();
这样做会引发错误。
ReflectionObject::__construct() expects parameter 1 to be object, string given in test.php on line 19
这是 php 5.5文档似乎显示我应该能够传递一个字符串。
http://php.net/manual/en/reflectionclass.construct.php
Either a string containing the name of the class to reflect, or an object.
知道吗?想要获取它们,而无需令牌解析文件。
就像@PeeHaa指出的那样,它不是ReflectionObject
而是ReflectionClass
。
新代码:
$reflection = new ReflectionClass( 'Foo' );
$staticProperties = $reflection->getStaticProperties();
ReflectionObject 提供有关对象实例的信息。您在问题中寻找和链接的是ReflectionClass。
尝试:
ClassName::propertyName
在这里:
ReflectionObject::getStaticProperties()
此链接直接取自 php 参考:http://php.net/manual/en/reflectionclass.getstaticpropertyvalue.php
<?php
class Apple {
public static $color = 'Red';
}
$class = new ReflectionClass('Apple');
var_dump($class->getStaticPropertyValue('color'));
?>
所以在这里你可以看到你需要一个类和一个静态属性的名称(请求的字符串)