Home > Article > Backend Development > PHP object-oriented final keyword usage and examples
In this lesson, let’s talk about the concept and usage of the final keyword.
What is the final keyword?
final Chinese translation is "final", "final". Modifying a class with the final keyword before declaring it means that this function will not be overloaded or inherited in any subclass. In other words, the class modified by final will not be able to have subclasses.
In the previous course, we talked about 4 types of keywords, public, private, protected, and static, which are public, private, protected, and static respectively. Usage and examples are all in the previous courses. Students who want to learn can refer to the previous courses:
php object-oriented static method use
php object-oriented Object data hiding
Let’s use examples to compare the difference between final and other keywords, and then analyze the usage of final:
Final usage examples detailed explanation:
<?php header("content-type:text/html;charset=utf-8"); class A{ //声明类 public $num = "23"; final function operation(){ //创建方法,用final关键字 echo '上面变量$num数字是 ' . $this->num ; } } class B extends A{ //创建子类B继承A类 public $num = "50"; function operation() { echo '这个变量$num数字是 ' . $this->num ; } } $Num = new B(); //实例化子类 $Num ->operation(); //调用子类中的方法
We first created a class A and added methods to class A, but we used final as the keyword before the method, that is to say, class A The method operation() in will no longer be inherited or overloaded. Then class B is created to inherit class A, including the method operation() that cannot be inherited. The result of the operation is only an error.
In the above example, overloading the operation() method in class A in class B is prohibited. Doing so will only result in an error.
If final is written before the class, then the entire class is prohibited from being inherited. For example, in the above example:
final class A{ }
Written like this, the entire class A will not be inherited or overloaded.
The above is the detailed content of PHP object-oriented final keyword usage and examples. For more information, please follow other related articles on the PHP Chinese website!