首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

final

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Example #1 Final methods example

代码语言:javascript
复制
<?php
class?BaseClass?{
???public?function?test()?{
???????echo?"BaseClass::test()?called\n";
???}
???
???final?public?function?moreTesting()?{
???????echo?"BaseClass::moreTesting()?called\n";
???}
}

class?ChildClass?extends?BaseClass?{
???public?function?moreTesting()?{
???????echo?"ChildClass::moreTesting()?called\n";
???}
}
//?Results?in?Fatal?error:?Cannot?override?final?method?BaseClass::moreTesting()
?>

Example #2 Final class example

代码语言:javascript
复制
<?php
final?class?BaseClass?{
???public?function?test()?{
???????echo?"BaseClass::test()?called\n";
???}

???//?Here?it?doesn't?matter?if?you?specify?the?function?as?final?or?not
???final?public?function?moreTesting()?{
???????echo?"BaseClass::moreTesting()?called\n";
???}
}

class?ChildClass?extends?BaseClass?{
}
//?Results?in?Fatal?error:?Class?ChildClass?may?not?inherit?from?final?class?(BaseClass)
?>

Note: Properties cannot be declared final, only classes and methods may be declared as final.

← Magic Methods

Object Cloning →

代码语言:txt
复制
 ? 1997–2017 The PHP Documentation Group

Licensed under the Creative Commons Attribution License v3.0 or later.

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com