Re: [VOTE] Userspace operator overloading
| From: | Terje Slettebø | Date: | Sun, 29 Mar 2020 21:33:04 +0000 |
| Subject: | Re: [VOTE] Userspace operator overloading | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-109430@lists.php.net to get a copy of this message | ||
Stanislav wrote:
C++ has a philosophy: "Trust the programmer." [1] While I understand that many are not amused by the overloading of ">>" and "<<" to mean input and output, the larger issue is that using such stream operators and function overloading provides an elegant and extensible way of providing reading and writing of user-defined types, usable for any stream. I know PHP is not C++, but other languages has been mentioned in this context, and another core tenet of the C++ language is that it's more important to provide useful abstractions, rather than banning anything that may be misused. Let's face it, you could make "add()" _subtract_ the numbers, or do strange things, just as well as you could do with a function overloading "+". Personally, I find it a greater gain in terms of code clarity to be able to write e.g.: $result = $a + $b * $c + $d; rather than: $result = $a->add($b->multiply($c))->add($d); Quick: Is the second one exactly identical to the first one? Yes, it is, but this one's got the associativity wrong: $result = $a->add($b)->multiply($c)->add($d); Would you catch that in code? There's a reason mathematicians have invented a set of symbols: It makes it easier to comprehend code using it, than if you only use function notation. We already know how to mentally parse expressions in terms of operator precedence, and having operator overloading follow the same rules means we can use that skill also for user-defined types. Regards, TerjeI think "as long as it is not overused" are the key words there. We have a very limited number of internal classes with operator overloadingI think the whole point of leaving it to extensions was ensuring it's not overused. And now I see people arguing "well, if it's available to extensions, then it also must be available to userspace" - which is the reverse of the premise under which it was implemented in the first place. Once we open this door, there's nothing that would prevent overuse and abuse - in fact, as we see, even having this door closed leads people to think since it exists, it must be used to the maximum, addition of userspace operator overloading will surely be taken as encouragement to be as creative as possible with overloading operators and inventing all kinds of incomprehensible and inconsistent operator schemes because it looked cool at the moment. So if anybody has hope it would "not be overused" - it will be.