From the string name of a class, can I get a static variable?(从一个类的字符串名称,我可以得到一个静态变量吗?)
问题描述
给定 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
这篇关于从一个类的字符串名称,我可以得到一个静态变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从一个类的字符串名称,我可以得到一个静态变量吗?


- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01