我一直这样做:
class Class1{
protected $myProperty;
public function __construct( $property ){
$this->myProperty = $property;
}
}
Run Code Online (Sandbox Code Playgroud)
但最近,我遇到了一种特殊的技术,如下所示:
class Class2{
protected $myProperty;
public function __construct( $property ){
$this->myProperty = $property;
return $this;
}
}
Run Code Online (Sandbox Code Playgroud)
在实例化此类时,可以这样做:
$property = 'some value';
$class1 = new Class1( $property );
$class2 = new Class2( $property );
Run Code Online (Sandbox Code Playgroud)
return $this构造函数中这一行的意义是什么,Class2因为无论有没有它,变量$class2仍将包含一个实例Class2?
编辑:请这与返回值的构造函数不同。我听说这个叫做流畅接口(用于方法链接)。我看过这个线程构造函数返回值?。我问的不是同一件事。我问的是意义return $this
返回那里没有任何用处$this。
他们很可能使用自动插入或类似的 IDE return $this,这对于方法链接很有用,但 return 语句__construct被丢弃。