1.final关键字(不能修饰属性,即变量)
a.希望一个类不被其他类来继承(出于安全性)
案例1:
<?php final class A { } class B EXTENDS A //此用法为错误 { ECHO "OK"; } ?>
结果:
Parse error: syntax error, unexpected T_ECHO, expecting T_FUNCTION in E:\Software_default\wamp_wwwroot\interface\interface05.phpon line 8
来自 <http://localhost/interface/interface05.php>
b.希望某个方法,不被子类改写,用final,对比案例2,案例3结果
案例2:没有重写
<?php class A { public function getrate($salary) { return $salary; } } class B extends A { } $b=new B(); echo $b->getrate(100); ?>
结果:
100
来自 <http://localhost/interface/interface06.php>
案例3:覆盖
<?php class A { public function getrate($salary) { return $salary; } } class B extends A // { public function getrate($salary) { return $salary*100; } } $b=new B(); echo $b->getrate(100); ?>
结果:
10000
来自 <http://localhost/interface/interface07.php>
案例4:禁止重写
<?php class A { final public function getrate($salary) { return $salary; } } class B extends A { public function getrate($salary) { return $salary*100; } } $b=new B(); echo $b->getrate(100); ?>
结果:
Fatal error: Cannot override final method A::getrate() in E:\Software_default\wamp_wwwroot\interface\interface08.phpon line 16
来自 <http://localhost/interface/interface08.php>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。