且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将属性声明为对象?

更新时间:2022-06-23 22:50:07

来自 关于类属性的 PHP 手册(重点是我的):

From the PHP manual on class properties (emphasis mine):

类成员变量称为属性".您可能还会看到使用其他术语(例如属性"或字段")来引用它们,但出于此引用的目的,我们将使用属性".它们是通过使用关键字 public、protected 或 private 之一来定义的,后跟一个普通的变量声明.这个声明可能包括一个初始化,但这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且必须不依赖于运行时信息才能被评估.

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)

Either create it inside the constructor (composition)

class Foo
{
    protected $bar;
    public function __construct()
    {
        $this->bar = new Bar;   
    }
}

注入 在构造函数中(聚合)

or inject it in the constructor (aggregation)

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

您希望赞成聚合而非组合.