【问题标题】:How do new Keyword works beside an object variable in PHP?新关键字如何在 PHP 中的对象变量旁边工作?
【发布时间】:2018-01-15 17:43:20
【问题描述】:

在研究 PHP 中的 OOP 时,我注意到 Here 中的 Example #5 Creating new objects 对象变量旁边使用的“new”关键字创建了一个新对象。
让我在这里举个例子:

    Class Test {
          function getInstance(){
           return new $this;
          }
   }

$Object1 = new Test();
$Object2 = $Object1->getInstance(); // this will create new object from the same class

另一个例子:

Class Test2{

}

$Object3 = new Test2();
$Object4 = new $Object3();// this will also create new object from the same class

The documentation 没有提及对此的任何声明,我也没有找到任何进一步的参考资料来澄清这个问题。

这是如何工作的,尽管使用 'new' 关键字的文档说明了以下规则:

如果包含类名的字符串与 new 一起使用,则会创建该类的新实例。如果该类位于命名空间中,则在执行此操作时必须使用其完全限定名。

【问题讨论】:

标签: php class keyword


【解决方案1】:

PHP Documentation 中引用了“示例#5”,其中描述了PHP 5.3.0 introduced a couple of new ways to create instances of an object

我对@9​​87654322@ 的回答更详细地解释了new class()new $class()clone $class 之间的区别

【讨论】:

  • 虽然是经典的 PHP 文档风格,但实际上从 PHP 5 开始就可以使用:3v4l.org/XtKLd
  • 奇怪的行为。
猜你喜欢
  • 1970-01-01
  • 2022-11-02
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
相关资源
最近更新 更多