__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