Is it possible to overload operators in PHP?
具体来说,我想创建一个Array类,并希望重载[]运算符。
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;
Actually, the optimal solution is to implement the four methods of the ArrayAccess interface: http://php.net/manual/en/class.arrayaccess.php
If you would also like to use your object in the context of 'foreach', you'd have to implement the 'Iterator' interface: http://www.php.net/manual/en/class.iterator.php
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
ArrayObject
is too slow for you). 下一篇: 是否有可能在PHP中重载运算符?