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
这篇关于从一个类的字符串名称,我可以得到一个静态变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从一个类的字符串名称,我可以得到一个静态变量吗?
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
