Edit report at https://bugs.php.net/bug.php?id=74198&edit=1
ID: 74198
Updated by: requinix@php.net
Reported by: cca dot alexk at gmail dot com
-Summary: Local static variable not update after create new
object of class
+Summary: static (variables) docs do not explain behavior in
class methods
Status: Open
-Type: Bug
+Type: Documentation Problem
Package: Variables related
Operating System: MacOS/Linux
PHP Version: 7.1.2
Block user comment: N
Private report: N
New Comment:
This is expected behavior: static variables defined in a class method are shared across all
instances of that class. Just like static properties.
The $bar in Foo(123)::foo and Foo(456)::foo are the same variable.
However I don't see this clearly documented - simply that variables don't lose value after
leaving scope - and it's not necessarily obvious that Foo::foo is really the same
function/method across every instance of Foo.
http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static
Previous Comments:
------------------------------------------------------------------------
[2017-03-02 11:40:41] cca dot alexk at gmail dot com
Description:
------------
Steps to reproduce:
1. Create object of class with method with local static variable
2. Assign value to this local variable
3. Create new object of that class
4. Check value of this variable
Test script:
---------------
<?php
class Foo
{
protected $bar;
public function __construct($bar)
{
$this->bar = $bar;
}
public function bar()
{
return $this->foo();
}
public function foo()
{
static $bar;
if (!$bar) {
$bar = $this->bar;
}
return $bar;
}
}
var_dump((new Foo(123))->bar());
var_dump((new Foo(456))->bar());
Expected result:
----------------
int(123)
int(456)
Actual result:
--------------
int(123)
int(123)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=74198&edit=1