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

兄弟間で共有されない子クラスごとに静的変数を作成するにはどうすればよいですか?

これを実行できるようにしたい理由は、親クラスから派生しているクライアントが上記の実装について心配する必要がなく、派生クラスごとに 1 回だけ発生するイベントを追跡できるようにするためです。追跡機能。ただし、上記のイベントが発生した場合、クライアントは確認できるはずです。

4

1 に答える 1

2

$_magical_static_proppertyはとの間で共有されるため、2 番目の入力が最初の入力よりも優先され、両方が同じものを表示します。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 に答える