On 11/08/2022 01:10, Larry Garfield wrote:
Would it be OK if extension methods came*before*  normal methods?


It would certainly be possible, and seems more logical than allowing extensions to over-ride __call but not anything else. It does lead to a very different feature, though: it means that you can take a fully working unit of code, add a "use extension" line at the top, and change the behaviour of that code.

I haven't looked in detail at how other languages implement them, but my impression is that such a behaviour change would be something other than an "extension method" as normally understood.


Would that allow a compile time translation of this:

use extension Foo:bar;

$collection->bar($b);

to this:

Foo::bar($collection, $b);


Unfortunately not, because the compiler doesn't know anything about the type of $collection, so doesn't know whether to apply the extension. The process would look something like this:

1. at compile-time, build a list of in-scope extension methods
2. before every method call, loop over the list, autoloading each entry if necessary 3. check each in-scope extension method in turn for an "instanceof" match against the current object
4. if one matches, despatch the call
5. if none matches, continue with the method call as normal


The lookup could be optimized in various ways (particularly if the user has to list every method they want to be in scope), but as far as I can see, giving extension methods higher priority will always be worse for performance, because the lookups will happen more often. Giving them lowest priority, just above throwing an error, is effectively free, unless you're doing something very weird and care about the performance of errors.

Regards,

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to