Hello!
I would like to suggest that static vars must allow expressions too.
Currently it only supports scalar values, but different to consts, it could
be manipulated by its own function that uses that.
https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.static
Currently you could uses like:
function test() {
static $x;
$x++;
var_dump($x);
}
test(); // 1
test(); // 2
So my idea is allow an initial value to be defined by a more complex
expression, like:
function test() {
static $configurationHandler = Configuration::getInstance();
$configurationHandler->doSomething();
}
Additionally, I thought that it might be necessary to implement some new
methods for ReflectionFunction / ReflectionMethod, in which it allows to
reset or check the current value.
(new ReflectionFunction('test'))->hasStaticVariable('x'); // true
(new ReflectionFunction('test'))->issetStaticVariable('x'); // true
(new ReflectionFunction('test'))->setStaticVariable('x', 123); // void
(new ReflectionFunction('test'))->getStaticVariable('x'); // 2
(new ReflectionFunction('test'))->unsetStaticVariable('x'); // void
or
(new ReflectionFunction('test'))->getStaticVariable('x'); //
ReflectionProperty (or ReflectionVariable)
One of the questions that can happen is about the context conflict, but it
already occurs:
class Test {
public function test(): void {
static $x = 0;
$x++;
var_dump($x);
}
}
(new Test)->test(); // 1
(new Test)->test(); // 2
Note that $x will share the context like a static property, even if it been
called from a non-static context.
Atenciosamente,
David Rodrigues
Hi David,
I would like to suggest that static vars must allow expressions too.
Currently it only supports scalar values, but different to consts, it could
be manipulated by its own function that uses that.
This idea was brought up 6 months ago with others in https://wiki.php.net/rfc/calls_in_constant_expressions_poll#vote
(See the poll for "Support calls in static variables")
The straw poll voting results were 14 against and 2 in favor of a limited subset of that functionality (and 0 for "any variable").
Even with more compelling examples and references,
and only focusing on one area, I personally doubt this would pass. (a 2/3 majority is required)
The 6 months period for repeating RFC ideas has passed.
The implementation for the corresponding RFC may be of use to anyone interested on working on similar areas,
but I'm currently not interested in doing further work on the implementation.
Thanks,
- Tyson