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

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

问题描述

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

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手册(强调我的):


类成员变量称为属性。您还可以使用其他术语(如属性或字段)查看它们,但为了参考的目的,我们将使用属性。它们是通过使用关键字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

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

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天全站免登陆