final从英文字面上很容易理解,翻译成中文就是“最终的”之意。在php面向对象编程中,final的应用主要有两个作用: 1、使用final修饰的类,该不能被继承 <?php final class Person { public $name; function __construct($name="" ) { $this->name =$name; } function say() { echo "我叫:". $this->name ."<br>" ; } } class student extends Person{//试图继承被final修饰的类,结果出错 } ?> | 程序运行结果:Fatal error: Class student may not inherit from final class (Person) in D:/PhpServer/wamp/www/phptest/parent.php on line 17 父类Person被final修饰后,即为最终版本,不能有子类,也不能对其进行扩展,你只能老老实实去引用它。 2、在类中被final修饰的成员方法,在子类中不能被覆盖 为防止子类扩展父类的方法可能给程序带来麻烦,同时也希望这个方法是“私有”的,是不能被扩展的,我们可以使用final关键字来修饰不需要被覆盖或者被扩展的方法。 <?php class Person { public $name; function __construct($name="" ) { $this ->name =$name; } final function say() { echo "我叫:". $this ->name ; } } class student extends Person{ function say() { //试图覆盖父类被final修饰的方法,结果出错 } } ?> | 程序调试结果: Fatal error: Cannot override final method Person::say() in D:/PhpServer/wamp/www/phptest/parent.php on line 19 总结:在php面向对象编程中使用final修饰的类,不能被继继。在类中使用final修饰的成员方法,在子类中不能被覆盖。 |