E
E
Evgeny Spiridonov2012-10-09 13:48:26
PHP
Evgeny Spiridonov, 2012-10-09 13:48:26

Behavior of static variables declared inside class methods?

I'm trying to figure out the scope of static variables declared inside class methods. To clearly demonstrate the situation, let's depict three such classes as an example:

abstract class ParentAbstract
  {
  public function __construct()
    {
    static $contructing_counter = 0; // Локальный счётчик конструктора
    $this->printValue('$contructing_counter', ++$contructing_counter);
    }
    
  public function someMethod()
    {
    static $method_counter = 0; // Локальный счётчик метода    
    $this->printValue('$method_counter', ++$method_counter);
    }
    
  protected function printValue($variable, $value)
    {
    echo get_class($this) . ' ' . $variable . ' = ' . $value . '<br />';
    }
  }
  
class ChildA extends ParentAbstract
  {
  }
  
class ChildB extends ParentAbstract
  {
  }

It seems that the behavior of local static variables of the constructor and method should be the same, but not - the static variable in the constructor remains visible (retains its value) for all descendant classes, but the method variable for each class turns out to be different.
You can verify this by running a simple example:
$object_a1 = new ChildA();
$object_a2 = new ChildA();
$object_b1 = new ChildB();
$object_b2 = new ChildB();

$object_a1->someMethod();
$object_a2->someMethod();
$object_b1->someMethod();
$object_b2->someMethod();

As a result of running the example, we get:
ChildA $contructing_counter = 1
ChildA $contructing_counter = 2
ChildB $contructing_counter = 3
ChildB $contructing_counter = 4
ChildA $method_counter = 1
ChildA $method_counter = 2
ChildB $method_counter = 1
ChildB $method_counter = 2

I would like to understand why?
Update: Runtime: PHP 5.2.17 (Windows)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AGvin, 2012-10-09
@AGvin

I also encountered this before.
I quote:

The thing is that at least we have two instances of the class, but the class as code is only one. Therefore, the static variable inside the constructor is also only one.

More details here:
http://blog.sjinks.pro/php/547-static-variable-inside-class-method/

E
EugeneOZ, 2012-10-10
@EugeneOZ

Global and static variables are a constant source of bugs and memory leaks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question