PHP 属性作为对象 [英] PHP property as object
本文介绍了PHP 属性作为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将类的属性设置为对象?
Is it possible to set a property of a class as a object?
喜欢:
class User {
public $x = "";
public $y = new ErrorVO();
public $w = new array();
}
推荐答案
在构造函数中,是的.
class User
{
public $x = "";
public $y = null;
public $w = array();
public function __construct()
{
$this->y = new ErrorVO();
}
}
编辑
KingCrunch 提出了一个很好的观点:你不应该对你的依赖项进行硬编码.您应该将它们注入您的对象(控制反转 (IoC)).
KingCrunch made a good point: You should not hard-code your dependencies. You should inject them to your objects (Inversion of Control (IoC)).
class User
{
public $x = "";
public $y = null;
public $w = array();
public function __construct(ErrorVO $y)
{
$this->y = $y;
}
}
new User(new ErrorVD());
这篇关于PHP 属性作为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文