【发布时间】: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 一起使用,则会创建该类的新实例。如果该类位于命名空间中,则在执行此操作时必须使用其完全限定名。
【问题讨论】:
-
@iainn:感谢提供的链接,非常有帮助。