Ger*_*rep 2 php types properties object
是否可以将类的属性设置为对象?
喜欢:
class User {
public $x = "";
public $y = new ErrorVO();
public $w = new array();
}
Run Code Online (Sandbox Code Playgroud)
在构造函数中,是的.
class User
{
public $x = "";
public $y = null;
public $w = array();
public function __construct()
{
$this->y = new ErrorVO();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
KingCrunch提出了一个很好的观点:您不应该对依赖项进行硬编码.您应该将它们注入对象(控制反转(IoC)).
class User
{
public $x = "";
public $y = null;
public $w = array();
public function __construct(ErrorVO $y)
{
$this->y = $y;
}
}
new User(new ErrorVD());
Run Code Online (Sandbox Code Playgroud)
只是我的首选解决方案,即使其他人已经解释了一切:注射
class A {
public $a;
public function __construct (ErrorVO $a) {
$this->a = $a;
}
}
Run Code Online (Sandbox Code Playgroud)
这使得类可以测试并且允许ErrorVO非常容易地替换想要的实现.当然,您可以将两种解决方案合二为一
class A {
public $a;
public function __construct (ErrorVO $a = null) {
$this->a = is_null($a) ? new ErrorVO : $a;
}
}
Run Code Online (Sandbox Code Playgroud)
次要更新:在此期间,您可以像这样编写第二个示例
class A {
public $a;
public function __construct (ErrorVO $a = null) {
$this->a = $a ?: new ErrorVO;
}
}
Run Code Online (Sandbox Code Playgroud)
它稍微紧凑一点,它使意图更清晰.将?:-operator与MySQL 进行比较COALESCE