PHP 中的 Final 关键字
phpserver side programmingprogramming更新于 2025/3/10 3:52:17
PHP 中 final 关键字用于方法和类。方法的 final 可防止方法覆盖,而具有 final 的类可防止继承。
示例
要在 PHP 中使用 final 关键字,代码如下。这里,我们有 final 方法−
<?php class Base { final function display() { echo "Base class function declared final!"; } function demo() { echo "基类函数!"; } } class Derived extends Base { function demo() { echo "派生类函数!"; } } $ob = new Derived; $ob->demo(); ?>
输出
将产生以下输出−
派生类函数!
示例
现在让我们看一个有 final 类 − 的示例
<?php final class Base { final function display() { echo "Base class function declared final!"; } function demo() { echo "基类函数!"; } } class Derived extends Base { function demo() { echo "派生类函数!"; } } $ob = new Derived; $ob->demo(); ?>
输出
这将产生以下输出,即由于我们尝试从最终基类创建派生类而导致的错误−
PHP Fatal error: Class Derived may not inherit from final class (Base) in /home/cg/root/6985034/main.php on line 19