Home  >  Article  >  Backend Development  >  Analysis of the difference between PHP custom constants and class constants

Analysis of the difference between PHP custom constants and class constants

伊谢尔伦
伊谢尔伦Original
2017-06-29 10:16:561469browse

1. Custom constants

The value of a constant can only be scalar data (boolean,integer,float and string) or null.

Once a constant is defined, it cannot be redefined or undefined.

There are two definition methods:

  • Use the define() function to define constants

define('STATUS', 3); // If the third parameter is set to true, the case is not sensitive

echo STATUS;

  • Use the const keyword to define constants

const NAME = 4;

echo NAME;

You can alsouse the function constant() to get the value of the constant.

Use the defined() function to check whether a constant with a certain name exists.


2. Class constants

Constants can be defined in a class. The value of a constant must be a fixed value and cannot be a variable, class attributeor the result of other operations (such as function calls). But in PHP5.6, constants have been enhanced to allow constant calculations and allow the use of expressionsresults containing numbers, stringsliteral values ​​and constants to define const constant. The value of a constant can also be an array, but not a variable.

Only the const keyword can be used to define class constants.

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;

Example:

/**
 * 1、define(name,value,case_insensitive) 自定义全局常量, 默认大小写敏感
 * 2、const 定义类常量。
 * 3、常量名前不要使用”$”
 * 4、常量的命名一般全部使用大写字母。
 */
//定义全局常量 LANGUAGE
define('LANGUAGE','中国');
echo language;//language
echo LANGUAGE;//中国
//定义全局常量 CN
define('CN','中国',TRUE);
echo CN;//中国
echo cn;//中国
//定义类常量
class ConstTest{
const VERSION = '1.0';
function ConstTest(){
//类内部使用“self::常量名”调用,不能使用$this
echo 'self::VERSION='.self::VERSION;
}
}
//实例化 ConstTest,目的是调用构造函数
new ConstTest();
//外部调用类常量,通过“类名::常量名”直接调用,无需实例化。
echo 'VERSION='.(ConstTest::VERSION);
echo &#39;<br>&#39;;
//array get_defined_constants ([ bool $categorize = false ] ) 返回所有已定义的常量
//print_r(get_defined_constants(true));
//bool defined ( string $name ) 检查该名称的常量是否已定义。
echo defined(&#39;cn&#39;)?&#39;true&#39;:&#39;false&#39;;

Print result:

language
中国
中国
中国
self::VERSION=1.0
VERSION=1.0
true

The above is the detailed content of Analysis of the difference between PHP custom constants and class constants. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn