If we do not want a class to be inherited, we use final to modify the class. This class cannot be inherited. Final --- used before classes and methods.
Final Class --- cannot be inherited.
Final method --- cannot be overwritten.
The final class cannot be inherited.
If we do not want a class to be inherited, we use final to modify the class. This class cannot be inherited. For example, the Math class we set involves the mathematical calculation methods we need to do. these algorithms do not need to be modified or inherited. we set them to the final type.
The code is as follows:
// Declare a final class Math
Final class Math {
Public static $ pi = 3.14;
Public function _ toString (){
Return "this is the Math class. ";
}
}
$ Math = new Math ();
Echo $ math;
// Declaration class SuperMath inherited from Math class
Class SuperMath extends Math {
}
// An error occurs during execution. The final class cannot be inherited.
?>
Program running result
The code is as follows:
Fatal error: Class SuperMath may not inherit from final class (Math) in E: \ PHPProjects \ test. php on line 14
The final method cannot be overwritten.
If you do not want a method in the class to be overwritten by the quilt class, we can set this method as the final method, just add the final modifier before this method.
If this method is overwritten by the quilt class, an error will occur.
The code is as follows:
// Declare a final class Math
Class Math {
Public static $ pi = 3.14;
Public function _ toString (){
Return "this is the Math class. ";
}
Public final function max ($ a, $ B ){
Return $ a> $ B? $ A: $ B;
}
}
// Declaration class SuperMath inherited from Math class
Class SuperMath extends Math {
Public final function max ($ a, $ B ){}
}
// An error occurs during execution. The final method cannot be overwritten.
?>
Program running result
The code is as follows:
Fatal error: Class SuperMath may not inherit from final class (Math) in E: \ PHPProjects \ test. php on line 16