在 PHP 中初始化静态成员 [英] Initialize static members in PHP
本文介绍了在 PHP 中初始化静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Person {
public static function ShowQualification() {
}
}
class School {
public static $Headmaster = new Person(); // NetBeans complains about this line
}
为什么这不可能?
我希望能够像这样使用
School::Headmaster::ShowQualification();
...无需实例化任何类.我该怎么做?
..without instantiating any class. How can I do it?
更新: 好的,我明白为什么部分了.有人可以解释如何部分吗?谢谢:)
Update: Okay I understood the WHY part. Can someone explain the HOW part? Thanks :)
推荐答案
来自 文档,
"像任何其他 PHP 静态变量一样,静态属性只能是使用文字或持续的;表达不是允许."
"Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed."
new Person()
不是文字或常量,所以这不起作用.
new Person()
is not a literal or a constant, so this won't work.
您可以使用变通方法:
class School {
public static $Headmaster;
}
School::$Headmaster = new Person();
这篇关于在 PHP 中初始化静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文