3

我很难理解构造函数中参数的类型提示和初始化。我偶然发现了这段代码:

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)。

如果我在普通函数中尝试第一个示例,如果我不提供参数,它会失败。

4

2 回答 2

2

首先,输入提示。它用于验证输入数据。例如:

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;
    }
}
于 2013-09-13T08:40:14.057 回答
0

好的,事实证明 Laravel 框架利用 PHP 的反射工具进行自动解析。案例已结束。感谢您尝试提供帮助!

Laravel 文档关于自动分辨率

于 2013-09-13T09:13:36.607 回答