Answer the question
In order to leave comments, you need to log in
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
{
}
$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();
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
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question