我很难理解构造函数中参数的类型提示和初始化。我偶然发现了这段代码:
class TabController {
protected $post;
protected $user;
public function __construct(Post $post, User $user)
{
$this->post = $post;
$this->user = $user;
}
}
我认为如果不是这样设置,参数不是可选的:
public function __construct(Post $post=NULL, User $user=NULL)
似乎这两个示例都初始化了一个空对象(不是 NULL)。
如果我在普通函数中尝试第一个示例,如果我不提供参数,它会失败。
首先,键入提示。它用于验证输入数据。例如:
class User {
protected $city;
public function __construct(City $city) {
$this->city = $city;
}
}
class City {}
class Country {}
$city = new City(); $user = new User($city); //all ok
$country = new Country(); $user = new User($country); //throw a catchable fatal error
其次,初始化空对象。这是按如下方式完成的:
class User {
protected $city;
public function __construct(City $city = null) {
if (empty($city)) { $city = new City(); }
$this->city = $city;
}
}
好的,原来Laravel框架利用PHP的反射工具进行自动解析。案件已结案。感谢您尝试提供帮助!
关于自动解析的 Laravel文档