从类的字符串名称,我可以得到一个静态变量?

Nat*_*ong 9 php static

给定PHP中类的字符串名称,如何访问其中一个静态变量?

我想做的是:

$className = 'SomeClass'; // assume string was actually handed in as a parameter
$foo = $className::$someStaticVar;
Run Code Online (Sandbox Code Playgroud)

...但PHP给了我一个可爱的"解析错误:语法错误,意外的T_PAAMAYIM_NEKUDOTAYIM",这显然是双冒号(::)的希伯来名字.

更新:不幸的是,我必须使用PHP 5.2.X.

更新2:正如MrXexxed猜测的那样,静态变量是从父类继承的.

Nat*_*ong 15

反思会做到这一点

一位同事刚刚向我展示了如何使用反射来实现这一点,它与PHP 5一起工作(我们在5.2上),所以我想我会解释一下.

$className = 'SomeClass';

$SomeStaticProperty = new ReflectionProperty($className, 'propertyName'); 
echo $SomeStaticProperty->getValue();
Run Code Online (Sandbox Code Playgroud)

请参见http://www.php.net/manual/en/class.reflectionproperty.php

类似的技巧适用于方法.

$Fetch_by_id = new ReflectionMethod($someDbmodel,'fetch_by_id');
$DBObject = $Fetch_by_id->invoke(NULL,$id);
// Now you can work with the returned object
echo $DBObject->Property1;
$DBObject->Property2 = 'foo';
$DBObject->save();
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/class.reflectionmethod.phphttp://www.php.net/manual/en/reflectionmethod.invoke.php


Vip*_*_Sb 7

您运行的是哪个版本的PHP?我相信在5.3.x以上这是允许的,但在此之前它不是.

编辑:这里你从PHP 5.3.0开始,它允许例#2

echo $classname::doubleColon(); // As of PHP 5.3.0
Run Code Online (Sandbox Code Playgroud)

编辑:对于变量使用

echo $classname::$variable; // PHP 5.3.0 +
Run Code Online (Sandbox Code Playgroud)

这是链接

编辑3:尝试此链接从那里的答案似乎它将适用于您的情况.