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

2022-01-05 00:00:00 static php

给定 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.

推荐答案

Reflection will do it

一位同事刚刚向我展示了如何使用反射来做到这一点,它适用于 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/en/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/en/反射方法.invoke.php

相关文章