本文介绍了声明属性作为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将类属性声明为对象?
How do you declare a class property as an object?
我试过:
public $objectname = new $Object();
但它没有工作。另外,为什么要这样做呢?
But it didn't work. Additionally, why should you do it like that?
只是实例化这个对象而只是使用它的成员不是更好吗?
Isn't it better to just instantiate that object and just use its members?
推荐答案
从(强调我的):
在建构函式中建立()
class Foo
{
protected $bar;
public function __construct()
{
$this->bar = new Bar;
}
}
或)
class Foo
{
protected $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
}
或使用setter注入。
or use setter injection.
class Foo
{
protected $bar;
public function setBar(Bar $bar)
{
$this->bar = $bar
}
}
您希望。
这篇关于声明属性作为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!