Home  >  Article  >  Backend Development  >  Application of php final keyword

Application of php final keyword

angryTom
angryTomforward
2019-10-14 15:25:012500browse

PHP 5 adds a new final keyword. If a method in the parent class is declared final, the child class cannot override the method. If a class is declared final, it cannot be inherited.

This keyword can only be used to define classes and methods. The final keyword cannot be used to define member properties, because final means constant. We use the define() function to define constants in PHP. , so final cannot be used to define member properties.

Classes marked with the final key cannot be inherited;

<?php
final class Person
{
    function say()
    {
    }
}
 
class Student extends Person
{
    function say() 
    {
    }
}
?>

The following error will occur:

Fatal error: Class Student may not inherit from final class (Person)

Methods using the final key mark cannot be overridden by subclasses and are the final version;

<?php
class Person
{
    final function say() 
    {
    }
 
}
class Student extends Person
{
    function say() 
    {
    }
}
?>

The following error will occur:

Fatal error: Cannot override final method Person::say()

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of Application of php final keyword. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.shuchengxian.com. If there is any infringement, please contact admin@php.cn delete