从一个类的字符串名称,我可以得到一个静态变量吗? [英] From the string name of a class, can I get a static variable?

查看:42
本文介绍了从一个类的字符串名称,我可以得到一个静态变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定 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.phphttp://www.php.net/manual/en/反射方法.invoke.php

这篇关于从一个类的字符串名称,我可以得到一个静态变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆