What is an elegant way to remove an object from an array of objects in PHP?
class Data{
private $arrObservers;
public add(Observer $o) {
array_push($this->arrObservers, $o);
}
public remove(Observer $o) {
// I NEED THIS CODE to remove $o from $this->arrObservers
}
}
You can do
You can also use
spl_object_hashto create a hash for the objects and use that as array key.However, PHP also has a native Data Structure for Object collections with
SplObjectStorage:SplObjectStorageisTraversable, so you canforeachover it as well.On a sidenote, PHP also has native interfaces for Subject and Observer.