我一直都做:
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 );
行返回$this在Class2的构造函数中的意义是什么,因为无论是否带有它,变量$class2仍将包含Class2的实例?
编辑:请这不同于返回值的构造函数.我听说这称为流利接口(用于方法链接).我看过这个线程Constructor returning value?.这不是我要问的问题.我要求返回$this的重要性
解决方法:
在那里没有返回$this的用处.
可能是他们使用的IDE会自动插入return $this或类似内容,这对方法链接很有用,但是__construct的return语句将被丢弃.
标签:constructor,php
来源: https://codeday.me/bug/20191027/1945397.html