如何在PHP中的对象中存储对象数组?

如何在PHP中的对象中存储对象数组?,php,Php,我希望我的对象的属性之一是另一种类型对象的数组 我如何表示它(即public$someObjectArray;) 向该属性添加条目的语法是什么 引用对象的语法是什么 提供一些(希望)有用的上下文 让我们假设对象是具有某些属性的属性,其中一个属性是具有自己属性(如姓名、年龄等)的多个租户 class Tenant { // properties, methods, etc } class Property { private $tenants = array(); pu

我希望我的对象的属性之一是另一种类型对象的数组

我如何表示它(即public$someObjectArray;)

向该属性添加条目的语法是什么

引用对象的语法是什么

提供一些(希望)有用的上下文

让我们假设对象是具有某些属性的属性,其中一个属性是具有自己属性(如姓名、年龄等)的多个租户

class Tenant {
    // properties, methods, etc
}

class Property {
    private $tenants = array();

    public function getTenants() {
        return $this->tenants;
    }

    public function addTenant(Tenant $tenant) {
        $this->tenants[] = $tenant;
    }
}
如果租户模型具有某种可识别属性(id、唯一名称等),您可以将其考虑在内,以提供更好的访问器方法,例如

class Tenant {
    private $id;

    public function getId() {
        return $this->id;
    }
}

class Property {
    private $tenants = array();

    public function getTenants() {
        return $this->tenants;
    }

    public function addTenant(Tenant $tenant) {
        $this->tenants[$tenant->getId()] = $tenant;
    }

    public function hasTenant($id) {
        return array_key_exists($id, $this->tenants);
    }

    public function getTenant($id) {
        if ($this->hasTenant($id)) {
            return $this->tenants[$id];
        }
        return null; // or throw an Exception
    }
}