次のコードのコメントは、私が何を達成しようとしているのかを示しています。これは非常に単純なことです__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