php - 如何在超类的静态方法中检索子类的静态属性
问题描述
我的情况类似于以下代码:
class ParentClass
{
public static $property = 'parentValue';
public static function doSomethingWithProperty() {
echo 'Method From Parent Class:' . self::$property . "\n";
}
}
class ChildClass extends ParentClass
{
public static $property = 'childValue';
}
echo "Directly: " . ChildClass::$property . "\n";
ChildClass::doSomethingWithProperty();
从 cli 运行它,我得到输出:
Directly: childValue
Method From Parent Class: parentValue
有没有办法从父类中定义的静态方法中检索子类中定义的静态属性?
解决方案
使用self
关键字总是引用同一个类。
要允许覆盖静态属性/方法,您必须使用static
关键字。你的方法应该是这样的
public static function doSomethingWithProperty()
{
echo 'Method From Parent Class:' . static::$property . "\n";
}
推荐阅读
- c# - Form.Show() 不允许键盘输入
- javascript - 跨多个图表的垂直线
- amazon-web-services - 如何将 SSL 证书从证书颁发机构复制到 EC2?
- python - 如何运行在 Spyder 的单独 .py 文件中定义的函数
- javascript - 反应状态无法更新
- algorithm - 在数组中找到最大差异 b/w 索引,约束 a[i]<=a[j] where i
这是我的代码,在一些测试用例中显示了错误的答案,谁能告诉我它在哪里失败了。即使经过多次尝试,我也无法弄清楚。
#include <iostream> using namespace std; int main() { //code int t,n; cin >> t; while
- mysql - 股票查询结果变量并发送电子邮件
- jboss - JBoss EAP 7.1 还支持吗?
- php - 如何在 silverstripe 的 SiteConfig 中设置属性?
- azure - 用于存储管理策略、选择性操作的 Terraform 模块