When autoloading in multiple classes that extend the same parent, they seem to overwrite each others static variables.
Using the code below, if the $staticvar
is only defined in the parent Controller
class then Foo::$staticvar
is overwritten by the subsequent called classes that also extend Controller
.
If however Foo itself also defines $staticvar = null;
then it is not overwritten. Why is this?
System.php
class System {
static function load() {
spl_autoload_register('System::autoload_controller');
$classes = array('Foo', 'Bar', 'Test');
foreach ($classes as $name) {
$instance = new $name;
}
}
static function autoload_controller($name) {
echo $name.":\n";
require_once strtolower($name).'.php';
$name::$staticvar = 'static_'.$name;
echo "Foo is: ".Foo::$staticvar."\n";
echo $name." is: ".$name::$staticvar."\n\n";
}
}
class Controller {
static $staticvar = null;
}
System::load();
If foo.php is this:
class Foo extends Controller {
}
I get the output:
Foo:
Foo is: static_Foo
Foo is: static_Foo
Bar:
Foo is: static_Bar
Bar is: static_Bar
Test:
Foo is: static_Test
Test is: static_Test
But if I change foo.php to this:
class Foo extends Controller {
static $staticvar = null;
}
I get the output:
Foo:
Foo is: static_Foo
Foo is: static_Foo
Bar:
Foo is: static_Foo
Bar is: static_Bar
Test:
Foo is: static_Foo
Test is: static_Test
If however Foo itself also defines $staticvar = null; then it is not overwritten. Why is this?
Because "static" means, it is static (bound) to the scope (class) where it is defined. This means Controller::$staticvar
and Foo::$staticvar
are two different properties.