Bug #48623 [Opn->Nab]: Incorrect scope for static variables in object methods
| From: | danack@php.net | Date: | Thu, 08 Jan 2015 20:40:54 +0000 |
| Subject: | Bug #48623 [Opn->Nab]: Incorrect scope for static variables in object methods | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-189750@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=48623&edit=1
ID: 48623
Updated by: danack@php.net
Reported by: falkon1313 at gmail dot com
Summary: Incorrect scope for static variables in object
methods
-Status: Open
+Status: Not a bug
Type: Bug
Package: Scripting Engine problem
Operating System: *
PHP Version: 5.2.10
Block user comment: N
Private report: N
New Comment:
Hi,
The static keyword inside a function or method has a different meaning to the meaning when used in a
class definition.
When used inside a function or method, a static variable exists only in a local function scope, but
it does not lose its value when program execution leaves this scope.
http://php.net/manual/en/language.variables.scope.php
Previous Comments:
------------------------------------------------------------------------
[2012-10-26 16:22:24] dagguh at gmail dot com
BTW. dont use ifs on non-boolean variables... YUCK!
You should write:
if (isset($val))
------------------------------------------------------------------------
[2012-10-26 16:21:14] dagguh at gmail dot com
Why the hell are you using the static keyword?
Use a class field, like normal people do:
<?php
class TestClass {
private $stored = 'empty';
public function test($val = NULL) {
if ($val) {
$this->stored = $val;
}
return $this->stored;
}
}
$a = new TestClass();
echo $a->test() ."\n";
echo $a->test('alpha') ."\n";
$b = new TestClass();
echo $b->test() ."\n";
echo $b->test('bravo') ."\n";
echo $a->test() ."\n";
TADA! Suddenly you get your expected result
------------------------------------------------------------------------
[2009-06-21 00:53:14] falkon1313 at gmail dot com
Description:
------------
When a variable is declared static within an object method, it's scope is spread across all
instantiated objects of the class.
This is not a static class variable, nor is it in a static class method, it is in a method that
requires an instantiated object, operates within the context of that object, and should have the
object scope.
Reproduce code:
---------------
<?php
class TestClass {
public function test($val = NULL) {
static $stored = 'empty';
if ($val) {
$stored = $val;
}
return $stored;
}
}
$a = new TestClass();
echo $a->test() ."\n";
echo $a->test('alpha') ."\n";
$b = new TestClass();
echo $b->test() ."\n";
echo $b->test('bravo') ."\n";
echo $a->test() ."\n";
Expected result:
----------------
empty
alpha
empty
bravo
alpha
Actual result:
--------------
empty
alpha
alpha
bravo
bravo
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=48623&edit=1