0

私は次のものを持っています:

class A
{
    public function getDependencies()
    {
        //returns A.default.css, A.default.js, A.tablet.css, A.tablet.js, etc,
        //depending on what files exist and what the user's device is.
    }
}

Aを拡張するクラスBでは、getDependenciesを呼び出すと、B.default.css、B.default.jsなどが取得されます。

私が今やりたいのは、BのgetDependencies()をオーバーライドすることなく、Aの結果も含めることです。実際、オーバーライドが機能するかどうかさえわかりません。これは可能ですか?

これは、テンプレートの動的CSS / JS読み込み、および最終的には本番用のコンパイルにも使用されます。

EDIT = getDependenciesが返すものは動的に生成され、保存された値のセットではないことを指摘しておく必要があります。

EDIT2 =私が持っている考えは、Aから継承するだけで動作が提供されるということです。おそらく、BからBの親、そしてAに至るまで、途中でメソッドをオーバーライドすることなく、階層ツリーを通過するある種の再帰が必要です。

4

3 に答える 3

2

使用parent::getDependencies()、例:

class B
{
  public function getDependencies()
  {
    $deps = array('B.style.js' 'B.default.js', 'B.tables.js' /*, ... */);
    // merge the dependencies of A and B
    return array_merge($deps, parent::getDependencies());
  }
}

すべての親を反復処理するために、ReflectionClassを使用するこのコードを試すこともできます。

<?php

class A
{
  protected static $deps = array('A.default.js', 'A.tablet.js');
  public function getDependencies($class)
  {
    $deps = array();

    $parent = new ReflectionClass($this);

    do 
    {
      // ReflectionClass::getStaticPropertyValue() always throws ReflectionException with
      // message "Class [class] does not have a property named deps"
      // So I'm using ReflectionClass::getStaticProperties()

      $staticProps = $parent->getStaticProperties();
      $deps = array_merge($deps, $staticProps['deps']);
    }
    while ($parent=$parent->getParentClass());

    return $deps;
  }
}
class B extends A
{
  protected static $deps = array('B.default.js');
}

class C extends B
{
  protected static $deps = array('C.default.js');
}

$obj = new C();
var_dump( $obj->getDependencies($obj) );

Ideone.comで

于 2012-05-25T14:03:05.853 に答える
1

リフレクションAPIを使用すると非常に簡単です。

親クラスを簡単に繰り返すことができます。

$class = new \ReflectionClass(get_class($this));
while ($parent = $class->getParentClass()) 
{
        $parent_name = $parent->getName();
        // add dependencies using parent name.
        $class = $parent;
}

適切な場所を教えてくれたComFreekの功績。

于 2012-05-25T15:07:46.837 に答える
0

selfキーワードを使用できます。これによりAクラスの値が返され、$thisを使用してBクラスの値を取得できます。

于 2012-05-25T13:58:00.580 に答える