Hi Dan,

Dan Ackroyd wrote:
I've written a small RFC to make it possible to call constructors of
objects as a callable, rather than only being able to call them
through the 'new' language construct.

https://wiki.php.net/rfc/callableconstructors

While I like the concept, I dislike the execution.

My particular concern is that this makes __construct magic. It is a so-called "magic method" already, which is why it is prefixed with two underscores, but like all magic methods, it isn't the method itself that is "magic". __construct itself is just a method, you can call it directly (for example, parent::__construct()). Where the magic lies is in what calls it: when an object is created with `new`, __construct is automatically called. Similarly, __toString is just a normal method you can call like any other, and is only "magic" because when an object is converted to a string, __toString is called.

Your proposal, however, would change this. Instead of __construct being a normal method which merely initialises the object it is called on, it would now become truly magical and actually implicitly create the object (without the author of the method having made it do so), but only in certain circumstances (not when called within a class, presumably). Furthermore, it becomes a strange beast PHP has not known until now: a method that is simultaneously static (Foo::__construct creates a new Foo) and an instance method (parent::__construct() operates on $this), with the two having different behaviour.

Instead of changing __construct to implicitly create the object it acts on in certain contexts, I would suggest a simpler approach: add a magic ::new() static method that exists on all classes (think ::class, although that is a constant). Foo::new() would work identically to new Foo(), and would solve your use case. It would be more intuitive, I think, and it avoids the problems of changing __construct.

Thanks.

--
Andrea Faulds
https://ajf.me/

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

Reply via email to