final---used before classes and methods.
Final class---cannot be inherited.
Final method---cannot be overridden.
Final classes cannot be inherited.
If we don’t want a class to be inherited, we use final to modify the class. This class will not be inherited. For example, the Math class we set involves the mathematical calculation methods we want to do. These algorithms do not need to be modified or inherited. We set it to a final type.
Copy code 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 inherits from Math class
class SuperMath extends Math {
}
//Execution error will occur , final classes cannot be inherited.
?> The code is as follows:
Fatal error: Class SuperMath may not inherit from final class (Math) in E:PHPProjectstest.php on line 14
The final method cannot be overridden
If we do not want a method in the class to be overridden by subclasses, we can set this method as a final method and just add the final modifier before this method. If this method is overridden by a subclass, an error will occur.
Copy code
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 inherits from Math class
class SuperMath extends Math {
public final function max($a,$b){}
}
//An execution error will occur, and the final method cannot be overridden.
?>
The code is as follows:
Fatal error: Class SuperMath may not inherit from final class (Math) in E:PHPProjectstest.php on line 16
http://www.bkjia.com/PHPjc/321642.html
www.bkjia.com
true
http: //www.bkjia.com/PHPjc/321642.html
TechArticle
final---used before classes and methods. final class---cannot be inherited. final method---cannot be overridden. Final classes cannot be inherited. If we don't want a class to be inherited, we use fina...
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn