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:
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