Function and operator overloading

From: Date: Sat, 28 Mar 2020 11:10:03 +0000
Subject: Function and operator overloading
Groups: php.internals 
Request: Send a blank email to internals+get-109380@lists.php.net to get a copy of this message
Hi. Please excuse me if this has been discussed to death earlier. I've tried to search for it, but I've come up empty: https://www.php.net/results.php? q=function+overloading&l=en&p=all The recent discussion on operator overloading has highlighted the relationship between function overloading and operator overloading, and how having support for the former may help provide the latter. For those with experience with C++, function and operator overloading works the same way, and the only difference is that operator overloading is defined as a function of the form "operator+(...)", i.e. "operator" followed by the operator itself. I know that C++'s system for overloading is very complex (because it has something called partial ordering of functions, and it also includes templates/generics). Nevertheless, I think it could be possible to implement a subset in PHP, without all the complexity, and in this way provide a cleaner way of implementing either kind of overloading, and avoiding the "closed set" / library interaction issues mentioned in the other thread. What I have in mind is to let the parameter types of a function become part of the function name, something like this: // Function overloads function add(Money $a, Money $b): Money { ... } function add(Matrix $a, Matrix $b): Matrix { ... } // Operator overloads function operator+(Money $a, Money $b): Money { ... } function operator*(Money $a, Percentage $b); Money { ... } function operator*(Matrix $a, Matrix $b): Matrix { ... } Use: $m1 = new Money(100); $m2 = new Money(200); $p = new Percentage(10); $result = $m1 + $m2; // Money(300) $result = $m1 * $p; Money(10) I realise that including the parameter types as part of the (internal) name of a function is a major departure from the way PHP works today. However, if we are to grow PHP into the future, and continue to provide clean ways of expressing things, then maybe we should re-examine such fundamental things, where a clean interface and simplicity for the developer is more important than implementation complexity. Regards, Terje

« previous php.internals (#109380) next »