|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[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
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Nov 20 22:00:01 2025 UTC |
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