我一直在做:
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接口(用于方法链接)。我看过这个线程构造函数返回值?。这与我所问的不一样。我询问return $this
的重要性
没有返回$this
的用途。
很可能他们使用的IDE会自动插入return $this
或类似内容,这对方法链接很有用,但__construct
的返回语句会被丢弃。
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.