Re: Concept: constructor overloading syntax sugar
| From: | Rowan Tommins [IMSoP] | Date: | Tue, 18 Feb 2025 08:00:22 +0000 |
| Subject: | Re: Concept: constructor overloading syntax sugar | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-126435@lists.php.net to get a copy of this message | ||
On 17 February 2025 14:39:42 GMT, Viktor Khramov <dev.999.victor@gmail.com> wrote:
>Hi!
>
>The point is here:
>https://gist.github.com/vhood/665418835e65be26d5a818fded92ab75
>Static functions look awful and break the object's API.
Personally, I think quite the opposite: named constructors make a lot more sense than type-based
overloads. For instance, you might have both createFromJson and createFromYaml; their inputs are
both going to be "string" as far as the type system is concerned, so overloading would be
useless.
Swift gets around this using "argument labels" which is sort of like requiring named
arguments and despatching based on those names, but I believe is actually derived from
SmallTalk's multipart method names.
Delphi is more explicit: a constructor is any class method marked with "constructor" in
its declaration, and the name "Create" is just a convention. It does also support
overloading on types, so other names are rarely used, which is a shame.
In your example, instead of this meaning different things based on what $a happens to hold:
$decision = new Decision($a, $b);
You could write one of these to be clear:
$decision = Decision::createFromId($a, $b);
$decision = Decision::createFromMail($a, $b);
Even if someone were to come up with a working implementation of overloading in PHP's type
system, I would probably oppose it, because I think it makes code harder to read and reason about.
Regards,
Rowan Tommins
[IMSoP]