Use a Class as an Attribute of Another Class

2019-09-19 07:35发布

问题:

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:

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

class business
{
    public $owner;
    public $type;

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


回答3:

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.



标签: php class