php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #16245 Static variables into class member funtions have wrong scope
Submitted: 2002-03-24 11:28 UTC Modified: 2002-06-17 14:34 UTC
From: flying at dom dot natm dot ru Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: 4.0.6 OS: Windows 2000 Server
Private report: No CVE-ID:
 [2002-03-24 11:28 UTC] flying at dom dot natm dot ru
 Static variables inside member functions of a classes have wrong scope. They should belong to each instance of a class, like normal class properties, but they're belong to class definition instead and, therefore, shared between every instance of this class. It makes static variables unusable into class member variables. 
 Here is an example:

// Define class
class A
{
    var $id = null;

    function A($id)
    {
        $this->id = $id;
    }

    function func()
    {
// Here we have counter into static variable
        static $cnt;
        if (!$cnt)
            $cnt = 0;
// Show counter value and ID of a class instance
        echo $this->id.": ".($cnt++)."\n";
    }
};

// Create 2 instances of our class with different IDs
$a = new A('A');
$b = new A('B');
// Call method of each class instance twice and see, 
// what will happen
$a->func();
$b->func();
$a->func();
$b->func();

Expected results:
-----------------
A: 0
B: 0
A: 1
B: 1

Actual results:
---------------
A: 0
B: 1
A: 2
B: 3


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-03-24 14:22 UTC] sander@php.net
I guess this is expected behaviour.
Reclassified as a documentation problem.
(BTW you can use global $cnt to overcome this problem)
 [2002-03-24 14:26 UTC] flying at dom dot natm dot ru
> I guess this is expected behaviour.

 I can't agree with it. If there is two separate instances of a class - they must have no common variables, but they have.

> Reclassified as a documentation problem.
> (BTW you can use global $cnt to overcome this problem)

 No, problem can be solved by having member variable instead of static.
 [2002-06-17 14:34 UTC] hholzgra@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php


 [2002-12-13 11:17 UTC] gandalf at alladyn dot art dot pl
Hmm... this _is_ a bug. Two instances should have anything common. 

class A{
	function ble(){
		global $x;
		static $r=0;
		print($r++.'<br>');
		$x->ble();
	}
}
$x=new A();
$y=new A();
$y->ble();

And we're down...

If it's not a bug than what is this? Proper behaviour?
 
PHP Copyright © 2001-2014 The PHP Group
All rights reserved.
Last updated: Sun Apr 20 05:03:19 2014 UTC