Re: [Concept] Extension methods
| From: | Ben Ramsey | Date: | Wed, 10 Aug 2022 16:18:41 +0000 |
| Subject: | Re: [Concept] Extension methods | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-118399@lists.php.net to get a copy of this message | ||
On 8/10/22 09:17, Alex Wells wrote:
Attachment: [application/pgp-signature] OpenPGP digital signature OpenPGP_signature.asc
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
Attachment: [application/pgp-signature] OpenPGP digital signature OpenPGP_signature.asc