Home >headlines >Declaration, assignment and output of PHP constants

Declaration, assignment and output of PHP constants

无忌哥哥
无忌哥哥Original
2018-06-28 09:34:143171browse

* 1. Three elements of constants:

* 1.1 Once created, it cannot be deleted or modified;

* 1.2 Do not add the '$' character in the header

* 1.3 Global scope, use

directly without declaration in the function * 2. Create:

* 2.1 Function: define('CONST_NAME', expression);

* 2.2 Keyword: const contName = static scalar, can be used in classes, cannot be used in functions

* 2.3 Constant names: usually only use uppercase letters and underlines, such as: ROOT_PATH

* 3. Access:

* 3.1 Keyword echo direct access: echo const_name;

* 3.2 Function: constant('constant name');

* 3.3 Function: get_defined_constants (): Get all constants

* 4. Detection: defined('constant name')

//Create constants

define('SITE_NAME','Peter Zhu的博客'); //函数define创建
const COUNTRY ='中国';  //关键字const创建

//Access constants

echo SITE_NAME,COUNTRY;  //关键字echo 访问
echo &#39;<hr>&#39;;
echo constant(&#39;SITE_NAME&#39;); //函数constant访问
echo constant(&#39;COUNTRY&#39;);  //函数constant访问
echo &#39;<hr><pre class="brush:php;toolbar:false">&#39;;

//Get all constants defined by the system, including user-defined

print_r(get_defined_constants()); 
echo &#39;<hr>&#39;;

//Detect constants

echo defined(&#39;SITE_NAME&#39;) ? &#39;已定义&#39; : &#39;未定义&#39;; //检测常量是否已声明
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
Previous article:php variable operationNext article:php variable operation