Php 是否可以为派生类创建静态属性,而不是为所有派生类创建静态属性?
我正在尝试实现如下内容:Php 是否可以为派生类创建静态属性,而不是为所有派生类创建静态属性?,php,inheritance,static,dynamic-binding,Php,Inheritance,Static,Dynamic Binding,我正在尝试实现如下内容: $child1_instance1 = new \aae\web\ChildOne(); $child1_instance2 = new \aae\web\ChildOne(); $child2_instance1 = new \aae\web\ChildTwo(); $child2_instance2 = new \aae\web\ChildTwo(); // setting the static variable for the first instanc
$child1_instance1 = new \aae\web\ChildOne();
$child1_instance2 = new \aae\web\ChildOne();
$child2_instance1 = new \aae\web\ChildTwo();
$child2_instance2 = new \aae\web\ChildTwo();
// 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
类结构与此类似:(我知道这不起作用。)
如何为每个未在兄弟姐妹间共享的子类创建静态变量
我希望能够做到这一点的原因是能够跟踪每个派生类只应发生一次的事件,而不必让从父类派生的客户端担心所述跟踪功能的实现。客户端应该能够检查所述事件是否发生。
$\u magical\u static\u property
在ChildOne
和ChildTwo
之间共享,因此第二个输入将胜过第一个输入,并且两个输入将显示相同的内容
演示:
解决此问题的唯一方法是为每个子级提供受保护的静态变量:
class ChildOne extends ParentClass {
protected static $_magical_static_propperty;
}
class ChildTwo extends ParentClass {
protected static $_magical_static_propperty;
}
演示:它会工作的。你的问题是什么?@hek2mgl:我澄清了我的问题,并在期望的输出下面添加了实际输出。谢谢你!检查Neals的答案。我忘了那件事。回答得好
class ChildOne extends ParentClass {
protected static $_magical_static_propperty;
}
class ChildTwo extends ParentClass {
protected static $_magical_static_propperty;
}