In-depth analysis of PHP final keyword usage tips ____php

Source: Internet
Author: User

Class inheritance in PHP is one of the most commonly used programming features, we can create a base class (the parent Class) and then define some basic methods in this, in our subclasses we can extend the methods in the parent class this is called overwrite, but if you're in some very critical way in the parent class you can't inherit the quilt class, Because if the subclass inherits this method may cause some trouble to the program, we hope this method is "private" and cannot be extended, which uses the final keyword in PHP to modify the method you are not inheriting.

The final keyword in PHP can modify the methods in the class as well, but they work the same way, that is, if you use the final keyword to decorate, the modified class or method will not be extended or inherited. You just have to quote it honestly. If you use final in front of the class, this means that the class cannot use inheritance; if you use the PHP final keyword before the method, this means that the method cannot be overwritten. The reason is so simple, let us also look at a simple example.

<?    PHP Final class BaseClass {public function test () {echo "baseclass::test () called\n";    The final public Function moretesting () {echo "baseclass::moretesting () called\n"; Class ChildClass extends BaseClass {public Function moretesting () {echo childclass::moretesting () Calle    D\n "; }//Results in Fatal Error:cannot override final Method baseclass::moretesting ()?>

In this example, we add the final PHP keyword before and after the class to modify our specific class, of course, this class is not required to output, you can do it yourself debugging, the basic principle of this, We just remember that if the class or method uses final then this means that the class cannot be inherited or that subclasses cannot override the parent class's methods.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.