AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > PHP编程

php面向对象之final的应用

51自学网 2016-09-17 http://www.wanshiok.com
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修饰的成员方法,在子类中不能被覆盖。


说明
:本教程来源互联网或网友上传或出版商,仅为学习研究或媒体推广,wanshiok.com不保证资料的完整性。
 
上一篇:php入门教程  下一篇:PHP开发时常用处理的操作类