php - 将属性声明为对象?

标签 php oop class

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

我试过:

 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/

相关文章:

java - 如何为其他泛型类声明抽象泛型父类(super class)?

php - 使用命名空间时找不到 SimpleXMLElement

php - 如何升级到 PhpStorm 8?

php - 使用 Eloquent ORM/laravel 准备好的声明

php - 命名抽象类

javascript - 无法在特定函数内运行类的函数

PHP数据库连接类问题

php - 我将如何在 sql 查询中执行数学运算来计算百分比差异?

php - 使用 PHPSECLIB 通过 SSH 与 RSA 连接

c# - Asp.net - 向类添加函数