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

Php 构造函数默认非可选参数初始化对象?,php,laravel,Php,Laravel,我很难理解构造函数中参数的类型暗示和初始化。 我偶然发现了以下代码: class TabController { protected $post; protected $user; public function __construct(Post $post, User $user) { $this->post = $post; $this->user = $user; } } 我认为如果不是这样设置的话,参数

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

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)

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

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

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的反射功能进行自动解析。。案件结案。谢谢你的帮助


如何创建实例?类型提示肯定不会创建对象。如果不提供默认值,使用
null
将参数设置为
null
。@Yoshi,是的,我就是这么想的。也许我错过了Chumkiu建议的实例创建中的某些内容。实际代码来自,我将尝试挖掘底层代码(除非构造函数中的类型暗示与我怀疑的根本不同,因此这个问题)。
Post$Post
意味着必须提供类型为
Post
的对象
Post$Post=null
表示该参数是可选的,可以是类型为
Post
null
/nothing的对象。不确定你的问题超出了这个范围。@deceze如果我只是用Post$Post初始化类,而不提供参数(我知道),它仍然初始化一个空的Post对象。我怀疑底层框架可能正在注入东西。