gpt4 book ai didi

php - 将属性声明为对象?

转载 作者:IT王子 更新时间:2023-10-29 00:12:02 25 4
gpt4 key购买 nike

如何将类属性声明为对象?

我试过:

 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
}
}

您想favor aggregation over composition .

关于php - 将属性声明为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com