The patch feature showcase: Operator overloading

at 2004-12-02 in PHP5 by friebe (0 comments)

"The patch" (still doesn't have a name yet) implements operator overloading in PHP5. Not all operators can be overloaded, however.


Operators           Overloadability
------------------- ----------------------------------------------------
++, --, !           These unary operators can be overloaded.
+, -, \*, /, %       These binary operators can be overloaded.
+=, -=, \*=, /=, %=  Assignment operators cannot be overloaded, but +=, 
                    for example, is evaluated using +, which can be 
                    overloaded.
== != < > <= >=     Comparison operators can be overloaded, but only
                    all of them at once, using the compare operator
                    (see below).


The key to operator overloading is the new keyword "operator". Apart from that, the syntax is equal to that of a normal method declaration:

Abbreviated example:

<?php 
class Integer {

public
static operator + (Integer $a, Integer $b) {
return
new Integer($a->value + $b->value);
}
}
?>

The comparison operator overloads all comparison operators:
- Equal ( == )
- Unequal ( != )
- Greater than ( > )
- Less than ( < )
- Greater than or equal to ( >= )
- Less than or equal ( <= )

The method must return one of the following:
- If the two values are equal: 0
- If the first value is smaller than the second: -1
- If the first value is bigger than the second: 1

Abbreviated example:

<?php 
class Integer {

public
static operator __compare (Integer $a, Integer $b) {
if
($a->value < $b->value) return -1;
if
($a->value == $b->value) return 0;
if
($a->value > $b->value) return 1;
}
}
?>


Now let's get to some useful purposes: As you might now, PHP's integer datatype ranges from -2147483648 to 2147483647 on 32-bit platforms and -9223372036854775808 to 9223372036854775807 on 64-bit platforms. Now what if you need to go beyond these ranges (especially on 32-bit systems)?

You could use the bcmath extension, of course. But now all of the calculations you could perform easily and readable using the built-in operators +, -, \* etc. would have to be replaced by ugly function calls.

The solution is simple: Define a class and overload these operators according to the rules defined above:)

See here for an example.



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases

Related

Find related articles by a search for «The».