如何将类属性声明为对象?
我试过:
public $objectname = new $Object();
但是没有用。此外,为什么要这样做?
只实例化那个对象并只使用它的成员不是更好吗?
最佳答案
来自 PHP manual on class properties (强调我的):
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value --that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
要么在构造函数中创建它(composition)
class Foo
{
protected $bar;
public function __construct()
{
$this->bar = new Bar;
}
}
或inject它在构造函数中(aggregation)
class Foo
{
protected $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
}
或者使用 setter 注入(inject)。
class Foo
{
protected $bar;
public function setBar(Bar $bar)
{
$this->bar = $bar
}
}
关于php - 将属性声明为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202995/