Consider the following array of objects:
class Person {
public $name;
public $occupation;
public function __construct($n, $o){
$this->name = $n;
$this->occupation = $o;
}
}
$people = array(
new Person("John", "singer"),
new Person("Paul", "guitar"),
new Person("George", "bass"),
new Person("Ringo", "drums")
);
Is there any quick way to access the objects? I wouldn't mind storing them in a different datatype (as opposed to array) if another datatype could make access easier.
Example of accessing an object: I would like to now change the "Paul" object to have an occupation of singer. This is the current solution:
foreach ( $people as &$p ) {
if ( $p->name=="Paul" )
$p->occupation="singer";
}
Alternatively, I might need to access based on a different property: Let's change all the singers' names to Yoko:
foreach ( $people as &$p ) {
if ( $p->occupation=="singer" )
$p->="Yoko";
}
Another example of accessing an object, this time in order to get the occupation of Ringo:
$ringosOccupation="";
foreach ( $people as $p ) {
if ( $p->name=="Ringo" )
$ringosOccupation = $p->occupation;
}
I suppose that I could write a People class that stores each Person object in an internal array and supplies functions to change or read occupation, but if PHP has anything cleverer build in I would love to know.
Thanks.