I seem to have trouble extending static classes in PHP.
PHP Code:
<?php
class InstanceModule {
public static $className = 'None';
public static function PrintClassName() {
echo self::$className . ' (' . __CLASS__ . ')<br />';
}
}
class A extends InstanceModule {
public static function Construct() {
self::$className = "A";
}
}
class B extends InstanceModule {
public static function Construct() {
self::$className = "B";
}
}
?>
My calling code, and what I'd expect:
<?php
//PHP Version 5.3.14
A::PrintClassName(); //Expected 'None' - actual result: 'None'
B::PrintClassName(); //Expected 'None' - actual result: 'None'
A::Construct();
A::PrintClassName(); //Expected 'A' - actual result: 'A'
B::PrintClassName(); //Expected 'None' - actual result: 'A'
B::Construct();
A::PrintClassName(); //Expected 'A' - actual result: 'B'
B::PrintClassName(); //Expected 'B' - actual result: 'B'
A::Construct();
A::PrintClassName(); //Expected 'A' - actual result: 'A'
B::PrintClassName(); //Expected 'B' - actual result: 'A'
?>
Actual complete output:
None (InstanceModule)
None (InstanceModule)
A (InstanceModule)
A (InstanceModule)
B (InstanceModule)
B (InstanceModule)
A (InstanceModule)
A (InstanceModule)
So what's going on here (from what it seems) is that as soon as I set self::$className
on either of the extending classes, it overrides the variable from the other class. I assume this is because I use static classes, and there can only be one InstanceModule
class instead of simply copying it to both A
and B
, as were my previous understanding of extends
. I've tried using the keyword static::$className
instead, but it seems to make no difference.
It'd be lovely if anyone could guide me in the right direction of what I'm doing wrong here, and what to do to fix this problem.
Edit: To clarify, this code does what I want, but is obviously a horrible workaround since it would ruin the whole idea of extending and reusing functions:
<?php
class A {
public static $className = 'None';
public static function PrintClassName() {
echo self::$className . ' (' . __CLASS__ . ')<br />';
}
public static function Construct() {
self::$className = "A";
}
}
class B {
public static $className = 'None';
public static function PrintClassName() {
echo self::$className . ' (' . __CLASS__ . ')<br />';
}
public static function Construct() {
self::$className = "B";
}
}
?>