Ancestors

Written by ignace nyamagana butera on 2025-02-01 at 19:33

Now that PHP8.4 support new MyClass()->method() without parentheses does it still make sense to add or have empty named constructor like MyClass::new() or MyClass::make() or MyClass::create()

[#]php84 #apidesign

=> More informations about this toot | More toots from nyamsprod@phpc.social

Toot

Written by Russell on 2025-02-01 at 21:24

@nyamsprod I've never been a fan of static constructor methods for any reason. Like that's the entire purpose of __construct and circumventing it feels ... off. Plus it's more often used to hide or enable singleton state that gives it an odor.

There's the argument about validating the shape/type/value or having convenience conversion methods (e.g. Vec2::from(Vec3)) but that friction should be an indicator of doing something wrong. Like it should be the Vec3 owns that logic.

¯_(ツ)_/¯ 2¢

=> More informations about this toot | More toots from zimzat@mastodon.social

Descendants

Written by ignace nyamagana butera on 2025-02-01 at 21:29

@zimzat

named constructors is PHP equivalent to method Overloading. I always take the example of a Geolocation value object class there is no single way to define geolocation so have the default constructor private and multiple named constructors on the same object sound logic/reasonable to me. But that's not the feature we are discussing here today

=> More informations about this toot | More toots from nyamsprod@phpc.social

Written by Russell on 2025-02-01 at 21:54

@nyamsprod Right, so then it depends on what the purpose of new/make/create is. "It depends"? 🤷‍♂️

Are methods called and then the instance discarded? Should use Dependency Injection instead.

Purely the syntactic sugar over (new X())->y()?

Is it a DTO with setters and a fluent interface?

With the Geolocation example there should still be one right way to make the object. E.g. public function __construct(public readonly float $longitude, public readonly float $latitude).

=> More informations about this toot | More toots from zimzat@mastodon.social

Proxy Information
Original URL
gemini://mastogem.picasoft.net/thread/113930736838880547
Status Code
Success (20)
Meta
text/gemini
Capsule Response Time
264.072049 milliseconds
Gemini-to-HTML Time
1.142524 milliseconds

This content has been proxied by September (3851b).