On Mon, Sep 2, 2019 at 4:03 PM Christian Schneider <cschn...@cschneid.com> wrote:
> Hi internals, > > While some people are trying to make PHP a stricter language I'm also > interested in making it a more flexible language by allowing to opt-in to > advanced features for people who want it. > Please don't shoot this down just because you are not the target audience > of such a feature ;-) > > Toying around with PHP 8 I noticed that it is now impossible to have > methods which can be called both statically and in an object. > This proposal brings back mixed mode methods both for extensions and a new > syntax for user-land functions to explicitly allow it. > > Motivation: > - Make migration of tried-and-tested mixed mode methods easier while > having to explicitly declare it. So yes, unchanged code gets the new > stricter semantics but updating code to the new (and from now on > well-defined) behaviour can be done by simply extending the function > definition. Having to rewrite such code to two different method names can > be tedious and error-prone without big benefit. > - Allowing mixed mode methods as a form of name-overload in cases having > to have two separate names for static/non-static is a WTF. > - Reviving things like > $elements = DOMDocument::loadXML($html)->childNodes; > instead of having to rewrite them to something like > ($dom = new DOMDocument)->loadXML($html); > $elements = $dom->childNodes; > by adding ZEND_ACC_ALLOW_STATIC to the method signature > (ext/dom/document.c currently still contains code to handle both cases). > > A first shot at an implementation was done using the syntax ?static and > using isset($this) to determine the current mode: > class A { > var $dynamic = 'dynamic'; > ?static function mixedmodefn() { return isset($this) ? > $this->dynamic : 'static'; } > } > allowing both (new A)->mixedmodefn() and A::mixedmodefn(). > > The implementation (including a test) can be found at > > https://github.com/php/php-src/compare/master...chschneider:optional_static > > If people are interested I could create an RFC for this. > I'm not in favor of this, but I'll also say that I don't hate it either. The big problem with what we had before was that any random instance method could also be used as a static method, which in 99% of the cases was not intended and would not work. Additionally, the engine had to always account for this edge-case possibility and perform extra checks that only rarely did something useful. Your proposal to use an explicit ?static annotation leaves this as a questionable coding pattern, but I don't see any big technical problems with it. Regards, Nikita