The base of constant _php in PHP object-oriented PHP5

Source: Internet
Author: User
Tags constant parse error
The constants defined in PHP5 are different from the method that defines the variable, and you do not need to add the $ modifier. Const PI = 3.14; That's OK.
Constant names that are defined using const are generally capitalized, which is a convention, as in any language.
This is also a convention if the defined constants are made up of multiple words, using the _ connection.
For example, max_mumber such a naming method. A good naming method that programmers must pay attention to.
A constant in a class is used like a static variable, except that its value cannot be changed. We use the class name:: Constant name to call this constant.

Copy Code code as follows:

?
Declare a final class math
Class math{
Const PI = 3.14;
Public Function __tostring () {
Return "This is the math class. ";
}
Here is a method of calculating the circle area. Using the const constant,
Note the use of methods similar to static variables.
Public final function Areaofcircular ($r) {
return $r * $r * self::P i;
}
Public final function Max ($a, $b) {
Return $a > $b? $a: $b;
}
}
echo Math::P i;
?>

Program Run Result:
Copy Code code as follows:
3.14

An error occurs when you try to assign a value to a constant that is defined by Const.
Copy Code code as follows:

?
Declare a final class math
Class math{
Const PI = 3.14;
Public Function __tostring () {
Return "This is the math class. ";
}
Here is a method of calculating the circle area. Using the const constant,
Note the use of methods similar to static variables.
Public final function Areaofcircular ($r) {
return $r * $r * self::P i;
}
Public final function Max ($a, $b) {
Return $a > $b? $a: $b;
}
Public function SETPI ($a) {
Self::P i = 3.1415;
}
}
echo Math::P i;
?>

Program Run Result:
Copy Code code as follows:
Parse error:parse Error in E:\PHPProjects\test.php on line 17

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.