Tuesday 27 March 2018

Is it possible to overload operators in PHP?



Specifically, I would like to create an Array class and would like to overload the [] operator.


Answer



If you are using PHP5 (and you should be), take a look at the SPL ArrayObject classes. The documentation isn't too good, but I think if you extend ArrayObject, you'd have your "fake" array.



EDIT: Here's my quick example; I'm afraid I don't have a valuable use case though:



class a extends ArrayObject {

public function offsetSet($i, $v) {
echo 'appending ' . $v;
parent::offsetSet($i, $v);
}
}

$a = new a;
$a[] = 1;

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...