php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #48623 Incorrect scope for static variables in object methods
Submitted: 2009-06-21 00:53 UTC Modified: 2015-01-08 20:40 UTC
Votes:2
Avg. Score:4.0 ± 1.0
Reproduced:2 of 2 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: falkon1313 at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.10 OS: *
Private report: No CVE-ID: None
 [2009-06-21 00:53 UTC] 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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-10-12 01:06 UTC] felipe@php.net
-Package: Class/Object related +Package: Scripting Engine problem
 [2012-10-26 16:21 UTC] 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
 [2012-10-26 16:22 UTC] dagguh at gmail dot com
BTW. dont use ifs on non-boolean variables... YUCK!
You should write:
if (isset($val))
 [2015-01-08 20:40 UTC] danack@php.net
-Status: Open +Status: Not a bug
 [2015-01-08 20:40 UTC] danack@php.net
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
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat May 04 05:01:30 2024 UTC