Think C#, make PHP

Operator overloading simulation for PHP.

PHP doesn’t support operator overloading. Cs2php is capable of simulating this feature while converting C# code to PHP.
Assume simple C# class

Class represents complex number. Some operators like multiplication has been defined in it. Following code represents ComplexNumber on PHP side.

Operator methods has been converted exactly like normal static methods. Method name was taken from C# (like op_Multiply) or from ScriptNameAttribute (like minus method).

Let’s take a look at operators usage.

And the same code in PHP

As you can see implicit conversion of a real number to a complex number was converted to a static method ComplexNumber::op_Implicit call. Moreover the addition and multiplication have been converted in similar way.

Of course CS2PHP can convert more complicated code, like this:

We can define more than one implementation for each operator. For example we can define two independent multiplication operators:

We have to decorate at least one definition with ScriptNameAttribute in order to specify different PHP names for both methods.

And now we can test this solution using following code:



Installed with WPInstant