Is it possible to overload operators in PHP? Specifically I would like to create an Array class and would like to overload the [] operator.
PHP's concept of overloading and operators (see Overloading, and Array Operators) is not like C++'s concept. I don't believe it is possible to overload operators such as +, -, [], etc.
Possible Solutions
- Implement SPL ArrayObject (as mentioned by cbeer).
- Implement Iterator (if
ArrayObject
is too slow for you). - Use the PECL operator extension (as mentioned by Benson).
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;
Put simply, no; and I'd suggest that if you think you need C++-style overloading, you may need to rethink the solution to your problem. Or maybe consider not using PHP.
To paraphrase Jamie Zawinski, "You have a problem and think, 'I know! I'll use operator overloading!' Now you have two problems."