在PHP构造函数中,return $this的作用是什么?

5

我一直在做:

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的重要性是什么。

3
没有用。 __construct() 方法没有返回值,它们总是返回 void。 - Andrei
2
链式方法调用(流畅接口) - Rizier123
你不需要返回 $this; "new" 关键字总是会返回对象。 - Thomas Rollet
可能是构造函数返回值?的重复问题。 - raina77ow
1
@Stephen,你不必在构造函数中返回 $this 以便链式调用。你可以简单地这样做:(new Class2(1))->getMyProperty();。另外,方法链和流畅接口是两个不同的概念。一个人可以使用方法链来实现流畅接口,但是方法链本身在链接调用中没有更大的语义,而流畅接口有,例如 $obj->setFoo()->setBar() 是方法链。$obj->select("…")->from("…")->where(…) 是一种用于构建内部领域特定语言的流畅接口。 - Gordon
显示剩余4条评论
2个回答

5

在此处返回$this没有用处。

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


使用它的开发人员是有意为之,而不是由IDE插入的。 - Stephen Adelakun
3
然后他们毫无意义地这么做了;因为有没有都没有任何区别......但是如果你知道他们是故意这样做的,也许可以问问他们为什么! - Mark Baker

2

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. 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接