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

return$this在php构造函数中有什么用途?,php,constructor,Php,Constructor,我一直在做: class Class1{ protected $myProperty; public function __construct( $property ){ $this->myProperty = $property; } } 但最近,我遇到了一种特殊的技术,比如: class Class2{ protected $myProperty; public function __construct( $property ){

我一直在做:

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
的实例


编辑:这与返回值的构造函数不同。我听说这个叫做fluent接口(用于方法链接)。我已经看过这条线了。我问的不是同一件事。我要问的是
返回$this
的意义在那里返回
$this
是没有用的


很可能他们使用的IDE会自动插入
return$this
或类似内容,这对方法链接很有用,但是
\uu构造的return语句被丢弃。

return$this在构造函数中不应有任何值。但是,当您希望连续调用函数时,如果它在类的任何其他函数中返回,我会看到一些值。例如:

class Student {
   protected $name;

   public function __construct($name) {
      $this->name = $name;
      //return $this; (NOT NEEDED)
   }

   public function readBook() {
      echo "Reading...";
      return $this;
   }

   public function writeNote() {
      echo "Writing...";
      return $this;
   }

}

$student = new Student("Tareq"); //Here the constructor is called. But $student will get the object, whether the constructor returns it or not.
$student->readBook()->writeNote(); //The readBook function returns the object by 'return $this', so you can call writeNote function from it. 

没有用
\uu constructs()
没有返回值,它们总是返回void;“new”关键字总是返回@Stephen的object可能的重复项。您不必从一个ctor返回$this,就可以从它链接。您只需执行
(新类2(1))->getMyProperty()。旁注:方法链接和Fluent接口是两码事。可以使用方法链接来实现Fluent接口,但是方法链接本身在链接调用中没有更大的语义,而Fluent接口有,例如
$obj->setFoo()->setBar()
是方法链接<代码>$obj->select(“…”)->from(“…”)->其中(…)
是一个流畅的接口,用于构建内部域特定语言。使用它的开发人员是故意这样做的,而不是通过IDE插入的。@StephenAdelakun-然后他们毫无意义地这样做了;因为不管有没有,都没有区别。。。。。但如果你知道他们是故意这么做的,那么也许可以问他们为什么!