Sorry, replying to all this time :)

I've missed to pinpoint an important fact: extensions don't add methods to
types per-say, rather they allow using them when imported. Extension's
methods would never be called if the extension isn't imported, which is
different from monkey-patching and runkit, where two parties could attempt
to define the same method twice and end up with only one of them left in
the runtime. This also means that it's perfectly fine for two extensions on
the same type and with the same method names to co-exist and be used
independently. Of course, unless you attempt to import both of them in a
scope of one file.

On Wed, Aug 10, 2022 at 7:18 PM Ben Ramsey <ram...@php.net> wrote:

> On 8/10/22 09:17, Alex Wells wrote:
>
> > The idea is to introduce extension methods, similar to those in Kotlin,
> C#,
> > Dart. For those unfamiliar, those are just regular functions with fancy
> > syntax. However, I think having those will not only improve readability,
> > but also cover some of the previously requested features.
>
> > Other languages (Kotlin [4], C# [5], Dart [6]) I'm aware of solve this
> > problem with extension methods. All of them use slightly different
> syntax,
> > but the main idea is:
> > - you define an extension method the same way you define a function,
> except
> > you specify which type you're extending
> > - you can use any type that a function can accept. This includes
> > primitives, classes, interfaces, traits and enums
> > - the type you're extending is implicitly bound to `$this`
> > - you only have access to the public scope - you can't access
> > private/protected members
> > - you have to import those the same way you import functions. You can't
> > define extensions globally
>
> I believe this is also called "monkey patching" in some places, and
> Ruby, Python, and JavaScript all offer some form of object extension
> similar to this.
>
> There is also the PHP runkit extension that provides some of the
> functionality you've described: https://www.php.net/runkit7
>
> --
> Cheers,
> Ben
>

Reply via email to