PHP Object-oriented final class and final method _php Foundation

Source: Internet
Author: User
Final---used before classes, methods.
The final class---cannot be inherited.
The 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 will not be inherited. For example, we set the math class, which involves the mathematical calculation methods we have to do, these algorithms are not necessary to modify, and there is no need to be inherited, we set it to final type.

Copy Code code 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;

Declaring class Supermath inherits from the math class
Class Supermath extends Math {
}
Execution can be an error and the final class cannot be inherited.

?>

Program Run Results

Copy Code code as follows:
Fatal Error:class Supermath may isn't inherit from final Class (Math) in E:\PHPProjects\test.php on line 14


Final method cannot be overridden
If you do not want a method in a class to override the quilt class, we can set this method to be the final method, with only the final modifier before this method.

If this method overrides the quilt class, an error will occur.
Copy Code code 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;
}
}
Declaring class Supermath inherits from the math class
Class Supermath extends Math {
Public final function Max ($a, $b) {}
}
Execution can fail and the final method cannot be overridden.

?>


Program Run Results

Copy Code code as follows:
Fatal Error:class Supermath may isn't 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.