Use of final keyword in PHP

Time:2022-1-2

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:
https://github.com/zhangyue0503/dev-blog/blob/master/php/201912/source/final%E5%85%B3%E9%94%AE%E5%AD%97%E5%9C%A8PHP%E4%B8%AD%E7%9A%84%E4%BD%BF%E7%94%A8.php

Reference documents:
https://www.php.net/manual/zh/language.oop5.final.php

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