我一直在做:
class Class1{
protected $myProperty;
public function __construct( $property ){
$this->myProperty = $property;
}
}
但最近,我遇到了一种特殊的技巧,如下所示:
class Class2{
protected $myProperty;
public function __construct( $property ){
$this->myProperty = $property;
return $this;
}
}
在实例化这个类时,可以这样做:
$property = 'some value';
$class1 = new Class1( $property );
$class2 = new Class2( $property );
在
Class2
的构造函数中,return $this
这一行的意义是什么?即使没有它,变量$class2
仍将包含Class2
的一个实例。请注意,这不同于构造函数返回值。我听说这被称为流畅接口(用于方法链接)。我已经查看了这个线程Constructor returning value?。但我的问题与此不同,我想知道return $this
的重要性是什么。
__construct()
方法没有返回值,它们总是返回 void。 - Andrei(new Class2(1))->getMyProperty();
。另外,方法链和流畅接口是两个不同的概念。一个人可以使用方法链来实现流畅接口,但是方法链本身在链接调用中没有更大的语义,而流畅接口有,例如$obj->setFoo()->setBar()
是方法链。$obj->select("…")->from("…")->where(…)
是一种用于构建内部领域特定语言的流畅接口。 - Gordon