I was wondering how you can define an array of objects within another object.
For example, let's say I have a class called "User", and another class called "Address".
A user can list an unlimited number of addresses. How do I do this?
My guess is that I need to declare an array of "Address" objects within the "User" class, but I am not sure how to do it.
Make a class, with a property that is an array, then add to the array:
<?php
class User
{
private $addresses = [];
public function addAddress(Address $address)
{
$this->addresses[] = $address;
}
public function getAddresses()
{
return $this->addresses;
}
}
class Address
{
private $street;
public function __construct($street)
{
$this->street = $street;
// ... etc
}
}
$user = new User();
$user->addAddress(new Address("Foo"));
$user->addAddress(new Address("Bar"));
var_dump($user->getAddresses());
You can declare it like this:
$user = new stdClass; // declare the user object
$user->firstName = "John"; // add firstName property
$user->lastName = "Doe"; // add lastName property
$user->addresses = array(); // add addresses property as an array
//declare a couple of dummy address objects
$address1 = new stdClass;
$adresss1->street = "Elm Street";
$address2 = new stdClass;
$adresss2->street = "Arlington Road";
//Add the generated address objects into the addresses array of the user
$user->adresses[] = $address1;
$user->adresses[] = $address2;
Let me know if this helps. Cheers!
class User {
private $address;
public function addAddress($street) {
$this->address[] = new Address($street);
}
public function getAddress($i) {
return $this->address[$i]->street;
}
}
class Address {
public $street;
public function __construct($s) {
$this->street = $s;
}
}
$u = new User;
$u->addAddress('abc');
$u->addAddress('def');
$u->addAddress('zzz');
echo $u->getAddress(2);