我正在尝试实现这样的东西:
$child1_instance1 = new aaewebChildOne();
$child1_instance2 = new aaewebChildOne();
$child2_instance1 = new aaewebChildTwo();
$child2_instance2 = new aaewebChildTwo();
// setting the static variable for the first instance of each derived class
$child1_instance1->set('this should only be displayed by instances of Child 1');
$child2_instance1->set('this should only be displayed by instances of Child 2');
// echoing the static variable through the second instance of each drived class
echo $child1_instance2->get();
echo $child2_instance2->get();
//desired output:
this should only be displayed by instances of Child 1
this should only be displayed by instances of Child 2
// actual output:
this should only be displayed by instances of Child 2
this should only be displayed by instances of Child 2
具有类似于这样的类结构:(我知道这不起作用。
abstract class ParentClass {
protected static $_magical_static_propperty;
public function set($value) {
static::$_magical_static_propperty = $value;
}
public function get() {
return static::$_magical_static_propperty;
}
}
class ChildOne extends ParentClass { }
class ChildTwo extends ParentClass { }
如何为每个未在同级之间共享的子类创建静态变量?
我希望能够这样做的原因是能够跟踪每个派生类只应该发生一次的事件,而不必让从我的父类派生的客户端担心所述跟踪功能的实现。客户端应该能够检查所述事件是否已发生。
> $_magical_static_propperty
在 ChildOne
和 ChildTwo
之间共享,因此第二个输入将胜过第一个输入,并且两者都将显示相同的内容。
演示:http://codepad.viper-7.com/8BIsxf
解决它的唯一方法是给每个子变量受保护的静态变量:
class ChildOne extends ParentClass {
protected static $_magical_static_propperty;
}
class ChildTwo extends ParentClass {
protected static $_magical_static_propperty;
}
演示:http://codepad.viper-7.com/JobsWR