在 PHP 中初始化静态成员

发布于 2024-09-03 06:26:31 字数 389 浏览 1 评论 0原文

class Person {
  public static function ShowQualification() {
  }
}

class School {
  public static $Headmaster = new Person(); // NetBeans complains about this line
}

为什么这是不可能的?

我希望能够像

School::Headmaster::ShowQualification();

..那样使用它,而无需实例化任何类。我该怎么做呢?

更新:好吧,我明白了为什么部分。有人可以解释一下如何部分吗?谢谢 :)

class Person {
  public static function ShowQualification() {
  }
}

class School {
  public static $Headmaster = new Person(); // NetBeans complains about this line
}

Why is this not possible?

I want to be able to use this like

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 :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╭ゆ眷念 2024-09-10 06:26:31

来自文档

“像任何其他 PHP 静态变量一样,
静态属性只能是
使用文字或初始化
持续的;表达式不是
允许。”

new Person() 不是文字或常量,因此这不起作用。

您可以使用解决方法:

class School {
  public static $Headmaster;
}

School::$Headmaster = new Person();

From the docs,

"Like any other PHP static variable,
static properties may only be
initialized using a literal or
constant; expressions are not
allowed."

new Person() is not a literal or a constant, so this won't work.

You can use a work-around:

class School {
  public static $Headmaster;
}

School::$Headmaster = new Person();
孤独患者 2024-09-10 06:26:31

new Person() 是一个操作,而不是一个值。

与任何其他 PHP 静态变量一样,
静态属性只能是
使用文字或初始化
持续的;不允许使用表达式。
因此,虽然您可以初始化静态
属性为整数或数组(例如
实例),你不能初始化它
到另一个变量,到一个函数
返回值,或一个对象。

http://php.net/static

您可以将 School 类初始化为一个对象:

class School {
  public static $Headmaster; // NetBeans complains about this line
  public function __construct() {
    $this->Headmaster = new Person();
  }
}

$school = new School();
$school->Headmaster->ShowQualification();

new Person() is an operation, not a value.

Like any other PHP static variable,
static properties may only be
initialized using a literal or
constant; expressions are not allowed.
So while you may initialize a static
property to an integer or array (for
instance), you may not initialize it
to another variable, to a function
return value, or to an object.

http://php.net/static

You can initialise the School class to an object:

class School {
  public static $Headmaster; // NetBeans complains about this line
  public function __construct() {
    $this->Headmaster = new Person();
  }
}

$school = new School();
$school->Headmaster->ShowQualification();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文