简体   繁体   中英

How do I store an array of objects within an object in PHP?

I would like one of the attributes of my object to be an array of another type of object.

How do I represent this (ie public $someObjectArray;)

What would be the syntax to add an entry to this attribute?

What would be the syntax to reference the object?

To provide some (hopefully) useful context.

Lets assume that the object is property which has some attributes one of which is a number of tenants who will have their own properties like name, age etc...

class Tenant {
    // properties, methods, etc
}

class Property {
    private $tenants = array();

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

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

If the Tenant model has some sort of identifiable property (id, unique name, etc), you could factor that in to provide better accessor methods, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM