1

我正在尝试实现这样的事情:

$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 { }

如何为每个子类创建不跨兄弟共享的静态变量?

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

4

1 回答 1

2

$_magical_static_propperty在and之间共享,因此第二个输入将胜过第一个输入,并且两者都将显示相同的内容。ChildOneChildTwo

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

于 2013-01-30T22:15:16.860 回答