In PhP5, constants defined by const are different from those defined by variables. You do not need to add a $ modifier. Const Pi = 3.14; then you can.
The constant names defined by const are generally capitalized. This is a convention, as is true in any language.
If the defined constant is composed of multiple words and uses _ join, this is also the Convention.
For example, max_mumber. A good naming method is:
Program Note.
Constants in a class are similar to static variables, but their values cannot be changed. We use the Class Name: constant name to call this constant.
CopyCode The Code is 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 for calculating the circular area. The const constant is used,
// Pay attention to the method used, similar to static variables.
Public final function areaofcircular ($ R ){
Return $ R * Self: PI;
}
Public final function max ($ A, $ B ){
Return $ A> $ B? $ A: $ B;
}
}
Echo Math: PI;
?>
Program running result:Copy codeCode: 3.14
An error occurs when you try to assign values to a constant defined by const.Copy codeThe Code is 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 for calculating the circular area. The const constant is used,
// Pay attention to the method used, similar to static variables.
Public final function areaofcircular ($ R ){
Return $ R * Self: PI;
}
Public final function max ($ A, $ B ){
Return $ A> $ B? $ A: $ B;
}
Public Function setpi ($ ){
SELF: Pi = 3.1415;
}
}
Echo Math: PI;
?>
Program running result:Copy codeThe Code is as follows: Parse error in E: \ phpprojects \ test. php on line 17