解释 PHP 中的 final 类和 final 方法。
phpobject oriented programmingprogramming更新于 2025/11/12 0:30:00
final 关键字是 PHP5 引入的,与面向对象编程概念有关。
但在讨论 final 之前,我们需要确保对继承概念有充分的理解。在继承中,我们可以从另一个类继承一个类。此外,我们可以重写继承类中的函数,以替换最初提供的行为。在某些情况下,我们可能需要阻止某个类被继承,或者我们可能需要防止某个函数被重写。这可以通过 final 来实现,通过在类和函数前加上 final 关键字。如果有人试图扩展 final 类或覆盖 final 函数,这实际上会导致 PHP 产生错误。
注意:
我们只能在方法和类中使用 final 关键字。
让我们借助以下示例来演示这个概念。
示例:
我们不能覆盖父类函数。
<?php
class BaseClass{
final function calculate($val1,$val2){
$sum = $val1+$val2;
echo "Sum of given no=".$sum;
}
}
class ChildClass extends BaseClass{
function calculate($x,$y){
$mult=$val1*$val2;
echo "Multiplication of given no=".$mult;
}
}
$obj= new ChildClass();
$obj->show(10,10);
?>
输出:
PHP Fatal error: Cannot override final method BaseClass::calculate()
解释:
在上面的例子中,BaseClass 类是父类。其中的 calculate 方法被标记为 final。这意味着我们不能在其任何子类中重写 show 方法。要识别错误, ChildClass 正在尝试定义 final 方法 show()。这将产生致命错误,这意味着父类的 final 方法不能在其子类中定义。
示例:
在类之前使用"Final"关键字
<?php
final Class BaseClass{
function printData($val1,$val2){
$add=$val1+$val2;
echo "Sum of given no=".$s;
}
}
class Child extends BaseClass{
function printData($val1,$val2){
$m=$val1*$val2;
echo "Multiplication of given no=".$m;
}
}
$obj= new Child();
$obj->printData(20,20);
?>
输出:
PHP Fatal error: Class Child may not inherit from final class (BaseClass)
解释:
在上面的例子中,BaseClass 类使用 final 定义,因此我们无法扩展该类。当 Child 类尝试从 BaseClass 扩展时(这意味着 Child 是 BaseClass 的子类)。对于这种情况,PHP 会抛出错误消息"Class Child 不能从 final 类(BaseClass)继承"。这意味着它不允许创建 BaseClass 的任何子类。

