Application of php final keyword

angryTom
Release: 2023-04-07 15:26:01
forward
2440 people have browsed it

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() 
    {
    }
}
?>
Copy after login

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() 
    {
    }
}
?>
Copy after login

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!

Related labels:
source:www.shuchengxian.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!