Operator overloading is a programming language features that allows operators to act differently depending on the type of data they are operating on. Since OOP lets us create custom types (classes), there are plenty of opportunities to do useful and interesting code manipulations using operator overloading.
Current operator overloading in PHP is somewhat limited. Most of it is contained in class methods delimited by two underscores (__) which are called magical functions. Currently available are string casting and automatic serializing / unserializing (you can read more about those in the manual). A native PHP5 extension called SPL (Standard PHP Library) implements some array operator overloading to provide iterateable objects, which was a very welcome addition in PHP5.
A recent article I read shows some very imaginative techniques to implement mathematical operator overloading using a PECL extension called opreator. The author’s implementations are very interesting, and he’s pushing for a native overloading implementation to make for a much easier use of such techniques.
Apparently, operator overloading is a recurring subject on the PHP internals. Developers coming to PHP from languages that support operator overloading natively have a tendency to request it as a language feature in PHP, but it appears to be a complex and loaded issue. There is even an issue opened on the matter in the PHP issue tracker, describing the lack of operator overloading in PHP as a bug.
Another thing to consider is that PHP already does some minor operator overloading – for example the plus operator (+) can be used on arrays to perform array merging. If you used the plus operator on two objects, how would it know whether to cast it into arrays or into numbers? Those ambiguities only add to the implementation headaches for the internal PHP dev team.
If those issues could be resolved, it would be very nice to have native magical methods such as __toArray() and __toNumber() which would open up a plethora of possible uses.
To know when the next article is published, please subscribe to new articles using your Email below or follow me on Twitter.