Re: Explicit constructor call and polymorphic dispatch

From: Date: Thu, 12 Jan 2017 19:25:18 +0000
Subject: Re: Explicit constructor call and polymorphic dispatch
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-97729@lists.php.net to get a copy of this message
On 1/12/2017 8:19 AM, Sebastian Bergmann wrote: > Am 12.01.2017 um 08:11 schrieb Tim Bezhashvyly: >> Disallow explicit call of __construct method > > I am baffled that this (still) works: > > $ cat /tmp/t.php > <?php > class C > { > public function __construct() > { > print __METHOD__ . PHP_EOL; > } > } > > $o = new C; > $o->__construct(); > > > $ php /tmp/t.php > C::__construct > C::__construct > > > $ php --version > PHP 7.1.0 (cli) (built: Dec 1 2016 07:39:00) ( NTS ) > Copyright (c) 1997-2016 The PHP Group > Zend Engine v3.1.0-dev, Copyright (c) 1998-2016 Zend Technologies > > I am in favor of an RFC to disallow explicit invocation of interceptor > methods such as __construct(). > > Can we do this in PHP 7.2 or does this have to wait for PHP 8? > https://github.com/php/php-langspec/blob/master/spec/14-classes.md#constructors > Constructors are called by object-creation-expression and from within > other (derived class) constructors. This suggests that creation is possible via the new keyword only and not via explicit calls to __construct. Hence, it could be categorized as unspecified and dropped in 7.2. However, there are other oddities that probably should be addressed too in the context of constructors which are actually defined and thus can only be removed in PHP 8. > A constructor can return a result, by value or byRef. > A constructor should not call its base-class constructor more than > once. ``` <?php // test.php class A { function __construct() { echo __CLASS__ , "\n"; } } class B extends A { function __construct() { parent::__construct(); echo __CLASS__ , "\n"; parent::__construct(); return "PHP\n"; } } $b = new B; echo $b->__construct(); ``` ``` $ php test.php A B A A B A PHP ``` Note that both PHP and HHVM implement this _correctly_: https://3v4l.org/DFGCa -- Richard "Fleshgrinder" Fussenegger

« previous php.internals (#97729) next »