Final in PHP

Source: Internet
Author: User
Tags final modifier

Final Chinese meaning is "last, final", can modify the class or method.

1) When you do not want a method of a parent class to be overloaded (override), you can modify it with the final keyword

2 When you do not want the class to be inherited, you can use the final modifier

Format:

Final Class class Name {

}

Class Name {

Final modifier function name (argument list) {}

}

1, if you want a class not to be inherited by other classes, you can use the final

Cases:

<?php
Final class a{
}
Class B extends a{//will have an error
}
echo "OK";
?>

2. If you want a method that is not overridden by any subclass, such as a method of calculating personal income tax, you can use final to modify the method.

<?php
Class a{
Final public Function getrate ($salary) {
return $salary *0.08;
}
}

Public Function Getrate ($salary) {
return $salary *0.01;
}
}
$b =new B ();
echo $b->getrate (2000); The runtime will complain because the getrate () in parent Class A is using the final decoration and cannot be overridden in a subclass
?>

3, by the final modified method, you can inherit the quilt class, but cannot override the quilt class

Cases:

<?php
Class a{
Final public Function getrate ($salary) {
return $salary *0.08;
}
}

/*public function Getrate ($salary) {
return $salary *0.01;
}*/
}
$b =new B ();
echo $b->getrate (2000); Output 160
?>

4, the final keyword can not modify attributes (variables)

Url:http://www.bianceng.cn/webkf/php/201612/50493.htm

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.