Home  >  Article  >  Backend Development  >  php--Final keyword

php--Final keyword

伊谢尔伦
伊谢尔伦Original
2016-11-23 13:56:401032browse

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.

Example #1 Final method example

class BaseClass
{
    public function test(){
        echo "BaseClass::test() called<br>";
    }
    final public function moreTesting(){
        echo "BaseClass::moreTesting() called<br>";
    }
}
class ChildClass extends BaseClass
{
    public function moreTesting(){
        echo "BaseClass::moreTeing called<br>";
    }
}

Example #2 Final class example

final class BaseClass{
    public function test(){
        echo "BaseClass::test() called\n";
    }
    //这里无论你是否将方法声明为final,都没有关系
    final public function moreTesting(){
        echo "BaseClass::moreTesting() called\n";
    }
}
class ChildClass extends BaseClass{}
//产生Fatal Error:Class ChildClass may not inherit from final class (BaseClass)

Note: Properties cannot be defined as final, only classes and methods can be defined as final.


Statement:
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
Previous article:php object copyNext article:php object copy