__CLASS__ 魔术常量很好地补充了 get_class() 函数。
有时您需要知道两者
- 继承类的名称
- 实际执行的类的名称
这是一个展示可能的解决方案的示例
<?php
class base_class
{
function say_a()
{
echo "'a' - said the " . __CLASS__ . "<br/>";
}
function say_b()
{
echo "'b' - said the " . get_class($this) . "<br/>";
}
}
class derived_class extends base_class
{
function say_a()
{
parent::say_a();
echo "'a' - said the " . __CLASS__ . "<br/>";
}
function say_b()
{
parent::say_b();
echo "'b' - said the " . get_class($this) . "<br/>";
}
}
$obj_b = new derived_class();
$obj_b->say_a();
echo "<br/>";
$obj_b->say_b();
?>
输出应大致如下
'a' - said the base_class
'a' - said the derived_class
'b' - said the derived_class
'b' - said the derived_class