What are the ways to define php constants?

hzc
Release: 2023-03-01 16:06:01
Original
4720 people have browsed it

What are the ways to define php constants?

What are the definition methods of PHP constants

Constant

Features: Cannot be modified, cannot Destroyed and cannot be deleted. After declaring a constant, the constant can be used anywhere on the page

Methods for declaring constants: const, define, static

Naming convention: and The variables are the same, but all capitalized

define: define is a function, which cannot be defined in an object, but can be defined and used in a class;

define('CL',10);
echo CL;
//判断常量是否存在
if(defined('CL')){
    echo 'ture';        
}else{
    echo 'false';
}
Copy after login

static: Static constant

Static constant: It is a variable that can be accessed using constant syntax, which is::, and can be accessed without instantiation

Note: static is only initialized once and called recursively will not be repeatedly initialized

 //定义静态常量    
 class Person{     
     public static $a = "呵呵";     
     public static function say(){      
         echo "我丢:".self::$a."<br>";     
         }    
      }    
    //输出静态属性    
    echo Person::$a."<br>";    
    //调用静态方法    
    Person::say();    
    //修改静态属性    
    Person::$a = "我靠";    
    echo Person::$a."<br>";
Copy after login

const: const is a language structure, which is faster than define when compiling. It is a global constant that can be defined in an object and used in a class. It can be understood as Class constants

 class CL    {            
  //定义常量       
   const CLS = &#39;常量值&#39;;       
   function a() {                
   //调用常量方法            
       echo self::CLS;            
  }    
}    
(new CL)->a();
Copy after login

Recommended tutorial: "php tutorial"

The above is the detailed content of What are the ways to define php constants?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template