Re: Explicit constructor call and polymorphic dispatch
| From: | Rowan Collins | Date: | Sun, 15 Jan 2017 17:34:55 +0000 |
| Subject: | Re: Explicit constructor call and polymorphic dispatch | ||
| References: | 1 2 3 4 5 6 7 8 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-97763@lists.php.net to get a copy of this message | ||
On 14/01/2017 14:58, Giovanni Giacobbi wrote:
If you go for blocking explicit calls to __construct() (i'm personally in favour of it), i hope you would change the syntax for its only legitimate use which is calling the parent's constructor within a constructor, so how about something like parent(...)? It would be ugly to say "You are not supposed to explicit call __construct() *ever*" and then "You know what, to initialize parent class you need to call __construct()".This is actually a very good point: if you ban calls to __construct, you need syntax for not only calling the parent constructor, but other constructors in the chain. For instance [https://3v4l.org/jTsek]: <?php class A {
public function __construct() {
echo 'A';
}
}
class B extends A
{
public function __construct() {
parent::__construct();
echo 'B';
}
}
class C extends B
{
public function __construct() {
// Skip parent constructor, but call grand-parent
A::__construct();
echo 'C';
}
}
new C;
Probably you could say "cannot call __construct directly, except in the __construct of a descendant class", but that all seems a bit fiddly.
I'm on the -1 side on this proposal, because the logical conclusion would be that all magic methods should be banned: __clone was already mentioned, but should you really be calling $foo->__get($bar) directly? If so, why is that more legitimate than $foo->__construct? And if not, do you allow parent::__get($bar), or do you insist on that using different syntax as well? (If you think the answers are easy for __get, pick a different magic method and ask the same questions).
These exceptions and special cases are going to proliferate, and all to stop a hypothetical "misuse" of the language. Do you have an example of a bug you've seen where a user acting reasonably would have been saved by this new prohibition?
Regards,
--
Rowan Collins
[IMSoP]