从类的字符串名称中,我可以获取静态变量吗?

问题描述:

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

Given the string name of a class in PHP, how can I access one of its static variables?

我想做的是这样

$className = 'SomeClass'; // assume string was actually handed in as a parameter
$foo = $className::$someStaticVar;

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

...but PHP gives me a lovely "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM", which apparently is a Hebrew name for the double colon(::).

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

Update: Unfortunately, I have to use PHP 5.2.X for this.

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

Update 2: As MrXexxed guessed, the static variable is inherited from a parent class.

反射会做到

一位同事刚刚向我展示了如何通过反射实现此功能,该功能可在PHP 5(我们在5.2上运行)中工作,所以我想我会解释一下.

Reflection will do it

A coworker just showed me how to do this with reflection, which works with PHP 5 (we're on 5.2), so I thought I'd explain.

$className = 'SomeClass';

$SomeStaticProperty = new ReflectionProperty($className, 'propertyName'); 
echo $SomeStaticProperty->getValue();

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

类似的技巧适用于方法.

A similar trick works for methods.

$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();

请参见 http://php.net/manual/en/class.reflectionmethod.php http://www.php.net/manual/zh/Reflectionmethod.invoke.php