构造函数默认的非可选参数初始化对象?

时间:2013-09-13 08:15:27

标签: php laravel

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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;
    }
}

答案 1 :(得分:0)

好的,事实证明Laravel框架利用PHP的Reflection工具进行自动解析。案例已关闭。谢谢你试图帮忙!

Laravel docs about Automatic Resolution

相关问题