将属性声明为对象? [英] declare property as object?

查看:44
本文介绍了将属性声明为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

来自 关于类属性的 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
    }
}

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

这篇关于将属性声明为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆