使用类作为另一个类的属性 [英] Use a Class as an Attribute of Another Class

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

问题描述

我想创建一个类,将另一个类的实例用作属性。类似的东西:

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;
}

这当然不起作用, 。我在Google搜索中发现的所有内容都只引用嵌套类定义( class a {class b {}} )。

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?

推荐答案

如果你打算调用其他类方法:

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);

这篇关于使用类作为另一个类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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