PHP Object-oriented final class and final method

Source: Internet
Author: User

Final---Used for classes, methods, and before.

The final class---cannot be inherited.

The final method---not be overwritten.

If we do not want a class to be inherited, we use final to modify the class. This class will not be inherited.

For example, we set up the math class, which involves the mathematical calculation methods we want to do, the algorithms are not necessary to modify, and there is no need to be inherited, we set it to the final type.

1<?2 //declaring a final class math3 Final classMath4 { 5      Public Static $pi= 3.14; 6 7      Public function__tostring ()8     { 9         return"This is the math class. "; Ten     }  One }  A $math=NewMath (); - Echo $math;  -  the //declaring class Supermath inherits from the math class - classSupermathextendsMath - {  - }  + //execution is an error and the final class cannot be inherited.  -  +?>

Program Run Results

Class Final class (Math) in E:\PHPProjects\test.php on line 16

If you do not want a method in the class to be overridden by the quilt class, we can set this method to be the final method, just precede the method with the final modifier.

If this method is overridden by the quilt class, an error will occur.

1<?2 //declaring a final class math3 classMath4 { 5      Public Static $pi= 3.14; 6      Public function__tostring ()7     { 8         return"This is the math class. "; 9     } Ten      Public Final function Max($a,$b) One     {  A         return $a>$b?$a:$b ;  -     }  - }  the //declaring class Supermath inherits from the math class - classSupermathextendsMath - {  -      Public Final function Max($a,$b){}  + }  - //execution is an error and the final method cannot be overridden.  +  A?>

Program Run Results

Class Final class (Math) in E:\PHPProjects\test.php on line 16

PHP Object-oriented final class and final method

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.