Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload operators in PHP?

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

like image 257
chadgh Avatar asked Apr 24 '09 21:04

chadgh


People also ask

Is it possible to overload 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.

How can we overload a method in PHP?

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.


3 Answers

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; 
like image 144
cbeer Avatar answered Sep 20 '22 01:09

cbeer


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

like image 34
panicz Avatar answered Sep 22 '22 01:09

panicz


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).
like image 21
grammar31 Avatar answered Sep 20 '22 01:09

grammar31