1. Custom Constants
the value of a constant can only be scalar data ( Boolean , integer , float and the string ) or null .
Once a constant is defined, it cannot be redefined or undefined.
There are two ways of defining this:
Define (' STATUS ', 3); Case is not sensitive if the third argument is set to True
Echo STATUS;
Const NAME = 4;
Echo NAME;
You can also use the function constant () to get the value of a constant.
Use the defined () function to check if a constant exists for a name.
2. Class constants
Constants can be defined in a class, and the value of a constant must be a fixed value and cannot be the result of a variable, class property, or other operation, such as a function call. in PHP5.6, however, constants are enhanced to allow constant computation, allowing the use of expression results that contain numbers, string literals, and constants to define const constants. The value of a constant can also be an array, but it cannot be a variable.
Defining a class constant can only use the const keyword.
Class MyClass { const AB = 2; Public Function Showconstant () { echo self::ab; }} echo myclass::ab; $obj = new MyClass (); $obj, Showconstant (); Myclass::showconstant (); $className = ' MyClass '; Echo $className:: AB;
Instance:
/** * 1, define (name,value,case_insensitive) custom global constants, default case Sensitive * 2, Const defines class constants. * 3, the constant name do not use "$" * 4, the name of the constant all use uppercase letters. *///defines global constants Languagedefine (' LANGUAGE ', ' China '); Echo language;//languageecho language;//China//define Global constants Cndefine (' CN ', ' China ', TRUE) echo cn;//China echo cn;//China//define class constant classes Consttest{const VERSION = ' 1.0 '; function consttest () {//class internally using "Self:: constant name" Call, Cannot use $thisecho ' self::version= '. self::version;}} Instantiate Consttest, the purpose is to call the constructor new Consttest ();//External call class constant, through the "class name:: Constant name" directly called, do not need to instantiate. Echo ' version= '. (consttest::version); Echo ' <br> ';//array get_defined_constants ([bool $categorize = false]) returns all defined constants//print_r (Get_defined_constants (true));//bool defined (string $name) checks that the constant for the name is defined. Echo defined (' CN ')? ' True ': ' false ';
Printing results:
Language China China Self::version=1.0version=1.0true