PHP object-oriented final class and final Method

Source: Internet
Author: User

Final --- used before classes and methods.
Final class --- cannot be inherited.
Final method --- cannot be overwritten.
The final class cannot be inherited.
If we do not want a class to be inherited, we use final to modify the class. This class cannot be inherited. For example, the math class we set involves the mathematical calculation methods we need to do. Algorithm There is no need to modify it, and there is no need to be inherited. We set it to the final type.

CopyCode The Code is as follows: <?
// Declare a final class math
Final class math {
Public static $ Pi = 3.14;

Public Function _ tostring (){
Return "this is the math class. ";
}
}
$ Math = new math ();
Echo $ math;

// Declaration class supermath inherited from math class
Class supermath extends math {
}
// An error occurs during execution. The final class cannot be inherited.

?>

ProgramRunning result

Copy code The Code is as follows: Fatal error: Class supermath may not inherit from final class (math) in E: \ phpprojects \ test. php on line 14

The final method cannot be overwritten.
If you do not want a method in the class to be overwritten by the quilt class, we can set this method as the final method, just add the final modifier before this method.

If this method is overwritten by the quilt class, an error will occur.Copy codeThe Code is as follows: <?
// Declare a final class math
Class math {
Public static $ Pi = 3.14;
Public Function _ tostring (){
Return "this is the math class. ";
}
Public final function max ($ A, $ B ){
Return $ A> $ B? $ A: $ B;
}
}
// Declaration class supermath inherited from math class
Class supermath extends math {
Public final function max ($ A, $ B ){}
}
// An error occurs during execution. The final method cannot be overwritten.

?>

Program running result
Copy codeThe Code is as follows: Fatal error: Class supermath may not inherit from final class (math) in E: \ phpprojects \ test. php on line 16

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.