是否可以为派生类创建静态属性,而不是从派生类派生的所有类?

时间:2013-01-30 21:54:40

标签: 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 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 { }

如何为不在兄弟姐妹之间共享的每个子类创建静态变量?

我希望能够做到这一点的原因是能够跟踪每个派生类应该只发生一次的事件,而不是从我的父类派生的客户端必须担心实现所述跟踪功能。如果所述事件已经发生,客户应该能够检查。

1 个答案:

答案 0 :(得分:2)

$_magical_static_proppertyChildOneChildTwo之间共享,因此第二个输入将胜过第一个,两者都会显示相同的内容。

演示: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