Use of final keyword in PHP


The use of the final keyword is very simple. The main function in PHP is to define non rewritable methods. What is a non rewritable method? Even after subclass inheritance, the method with the same name cannot be redefined.

class A {
    final function testA(){
        echo 'This is class A!', PHP_EOL;

class childA extends A {
    //  Fatal error: Cannot override final method A::testA()
    function testA(){
        echo 'This is class childA', PHP_EOL;

If you add this keyword before the class definition, the class is also not inheritable.

final class B {
    function testB(){
        echo 'This is class B!', PHP_EOL;

// Fatal error: Class childB may not inherit from final class (B)
class childB extends B{


Thus, the final keyword has the same meaning as itself. This class or method cannot be changed. Can the interface use this keyword? Of course, the answer is No. the meaning of the interface itself is to define a contract for the implementation class to implement. If the final keyword is defined, the meaning of the interface does not exist. Therefore, from the language level, the final keyword cannot be used for the interface and the methods in the interface.

interface C {
    // Fatal error: Access type for interface method C::testC() must be omitted 
    final function testC();

In Java, final can also be used to define constants, but in PHP, class constants are defined through const. So final cannot define variables.

Test code:

Reference documents:

Official account: hard core project manager

Add wechat / QQ friends: [xiaoyuezigonggong / 149844827] get free PHP and project management learning materials

Tiktok, official account, voice, headline search, hard core project manager.

Station B ID: 482780532