Next: , Previous: , Up: Top   [Contents]


1 Operator Overloading

Operator overloading is a syntactic sugar available in various programming languages (e.g. C++, Python, Kotlin). This feature contributes to cleaner and more expressive code when performing arithmetic-like operations on objects.

For example, when using a Complex class in PHP, you may want to:

$a = new Complex(1.1, 2.2);  // 1.1 + 2.2j
$b = new Complex(1.2, 2.3);  // 1.2 + 2.3j

$c = $a * $b / ($a + $b);

Instead of:

$c = $a->mul($b)->div($a->add($b));

Although there is an RFC to provide this feature for PHP, it’s not yet taken into consideration, which means we can’t simply overload operators in userland PHP.

Fortunately, operator overloading can be achieved in native PHP with a little bit of invocation to several Zend APIs, without having to temper with any internal code of the PHP interpreter. The PECL operator extension already does that for us (the releases are out of date, see the git master branch for PHP7 support).

In this article, we will talk about the details of implementing operator overloading in a native PHP extension. We assume that the readers know the basics of the C/C++ programming language and basics of the Zend implementation of PHP.