Specifically, I would like to create an Array class and would like to overload the [] operator.
These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator.
To achieve method overloading in PHP, we have to utilize PHP's magic methods __call() to achieve method overloading. __call(): In PHP, If a class executes __call(), and if an object of that class is called with a method that doesn't exist then, __call() is called instead of that method.
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).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With