PHP object-oriented final class and final method

Source: Internet
Author: User
If we do not want a class to be inherited, we use final to modify the class. This class cannot be inherited. 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. these algorithms do not need to be modified or inherited. we set them to the final type.

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.

?>

Program running result

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.
The 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

The 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.