Mixed mode methods
| From: | Christian Schneider | Date: | Mon, 02 Sep 2019 14:03:08 +0000 |
| Subject: | Mixed mode methods | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-106829@lists.php.net to get a copy of this message | ||
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.
Regards,
- Chris