Home  >  Article  >  Backend Development  >  const define difference PHP

const define difference PHP

王林
王林Original
2019-10-14 17:57:472115browse

const define difference PHP

When defining constants in PHP, there are two methods: const and define. So what is the difference between them?

1. Const is used to define class member variables. Once defined, its value cannot be changed. define defines global constants and can be accessed anywhere

2. define cannot be defined in a class, but const must be defined in a class, and variables defined by const must be accessed through class name::variable name

3. const cannot define constants in conditional statements

<?php
    if(1){
        const a = &#39;java&#39;;
    }
    echo a;  //必错
?>

4. const uses an ordinary constant name (static scalar), and define can use any expression as the name

<?php
const  FOO = &#39;PHP&#39;; 
for ($i = 0; $i < 32; ++$i) { 
    define(&#39;PHP_&#39; . $i, 1 << $i); 
} 
?>

5. const is always case-sensitive. However, define() can define case-insensitive constants through the third parameter.

6. Using const is simple and easy to read. It itself is A language structure, and define is a method. Using const to define is much faster than define at compile time

Recommended tutorial:PHP video tutorial

The above is the detailed content of const define difference PHP. 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
Previous article:How to build php in iisNext article:How to build php in iis