Edit report at https://bugs.php.net/bug.php?id=48623&edit=1

 ID:                 48623
 Comment by:         dagguh at gmail dot com
 Reported by:        falkon1313 at gmail dot com
 Summary:            Incorrect scope for static variables in object
                     methods
 Status:             Open
 Type:               Bug
 Package:            Scripting Engine problem
 Operating System:   *
 PHP Version:        5.2.10
 Block user comment: N
 Private report:     N

 New Comment:

BTW. dont use ifs on non-boolean variables... YUCK!
You should write:
if (isset($val))


Previous Comments:
------------------------------------------------------------------------
[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

Reply via email to