I have a magic __set($name, $value) method. Within __set(), Is there a way I can detect if the array append short-hand was used so it doesn’t blow away pre-existing values?
class Foo extends ArrayObject {
protected $bar = array();
public function __set($name, $value) {
$this->bar = $value; // I want to handle both replace AND append
}
}
$foobar = new Foo;
$foobar->bar = array('first element');
$foobar->bar[] = 'new element';
How can I handle this situation?
You can use
__getto achieve what you want.This is because the
[]=operation first reads the property, then appends the element.Note that
__getmust return ‘by reference’ for this to work (at least in PHP 5.4); if it does not return by reference you get a notice about indirect modification.NOTE: also, at this point, you’d probably be as well making it public as the effect is basically the same.