Use a Class as an Attribute of Another Class

元气小坏坏 提交于 2020-01-25 14:31:32

问题


I would like to create a class with an instance of another class used as an attribute. Something like this:

class person
{
    var $name;
    var $address;
}

class business
{
    var $owner = new person();
    var $type;
}

This, of course, does not work, and I have tried a few variations. Everything I have found in Google searches only references nested class definitions (class a { class b{ } }).

Is it possible to put a class instance in another class? If not, is there a reasonable work-around?


回答1:


may be try using like this if your intention is to call other class method:

class person
{
    public $name;
    public $address;
}

class business {
 public $owner;
    function __construct( $obj ) {
        $this->owner = $obj;
    }

}   
$a = new person();
$b = new business($a);



回答2:


You can't initialize classes as part of a attribute/property/field declaration.

From the PHP Property documentation:

[Property] 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.

If you need the new instance to have a property that contains a class instance, you need to assign it in the constructor:

class business {
    public $owner;

    public function __construct() {
        $this->owner = new person();
    }
}

As an aside, be sure to use visibility keywords (public, protected, private) rather than var.




回答3:


class person
{
    public $name;
    public $address;
}

class business
{
    public $owner;
    public $type;

    public function __construct()
    {
        $this->owner = new person();
    }
}


来源:https://stackoverflow.com/questions/27532012/use-a-class-as-an-attribute-of-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!