0

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

How do I represent this (i.e. 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...

1 Answer 1

1
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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.