php 构造函数中的 return $this 有什么用?

Ste*_*kun 5 php constructor

我一直这样做:

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

cwa*_*ole 5

返回那里没有任何用处$this

他们很可能使用自动插入或类似的 IDE return $this,这对于方法链接很有用,但 return 语句__construct被丢弃。

  • @StephenAdelakun - 然后他们毫无意义地这样做了;因为有或没有,绝对没有区别……但如果你知道他们是故意的,那么也许可以问他们为什么! (3认同)