1

次のコードのコメントは、私が何を達成しようとしているのかを示しています。これは非常に単純なことです__CLASS__。これは、現在のクラスではなく親クラスを参照します (例:parent::__CLASS__コードには表示されませんが、サブサブクラスがある場合、そのようなクラス内でparent::parent::__CLASS__ifのような方法で親クラスを参照できるようにしたい)可能な限り)。

class ParentClass {

  protected $foo;

  function __construct() {

    $this->foo = "hello";

  }

}

class DerivedClass extends ParentClass {

  public $bar;

  public $baz;

  function __construct($bar) {

    // I want to be able to write
    // something like parent:__CLASS__
    // here in place of 'ParentClass'
    // so that no matter what I rename
    // the parent class, this line will
    // always work. Is this possible?

//      if (is_a($bar, parent::__CLASS__)) {

    if (is_a($bar, 'ParentClass')) {

      $this->bar = $bar;

    } else {

      die("Unexpected.");

    }

    $this->baz = "world";

  }

  public function greet() {

    return $this->bar->foo . " " . $this->baz;

  }

}

$d = new DerivedClass(new ParentClass());
echo $d->greet();

出力:

hello world
4

2 に答える 2

1

get_parent_classそれを行うには関数が必要です。

function __construct($bar) {

    $parent = get_parent_class($this);


    if (is_a($bar, $parent)) {

      $this->bar = $bar;

    } else {

      die("Unexpected.");

    }

    $this->baz = "world";

  }

さらにレベルを下げる必要がある場合は、次を使用できます。

class subDerivedClass extents DerivedClass{
    $superParent = get_parent_class(get_parent_class($this));
}
于 2015-02-08T23:54:07.303 に答える
1

PHP 5.5 では、キーワード::classを使用してクラスの親の名前を取得できますが、a) クラス内から、b) 1 レベル上、つまり直接の親の祖先でのみ機能します。

function __construct($bar) {
   if ($bar instanceof parent::class) {
      ...
   }
}

私が行く最善の解決策はチェーンget_parent_classです:

if ($bar instanceof get_parent_class(get_parent_class())) {
    ...
}

または、リフレクションによるメソッド チェーン:

$parent_class = (new Reflection($this))->getParentClass()->getParentClass()->getName();

if ($bar instanceof $parent_class) {
    ...
}
于 2015-02-08T23:58:37.507 に答える