Home > Backend Development > PHP Tutorial > Analysis of the difference between const and define in php

Analysis of the difference between const and define in php

WBOY
Release: 2016-07-25 08:58:30
Original
1020 people have browsed it
  1. if (...) {
  2. const FOO = 'BAR'; // invalid
  3. }
  4. but
  5. if (...) {
  6. define('FOO', 'BAR'); // valid
  7. }
Copy code

4. const uses an ordinary constant name, and define can use an expression as the name. For example:

  1. const FOO = 'BAR';
  2. for ($i = 0; $i < 32; ++$i) {
  3. define('BIT_' . $i, 1 << $i );
  4. }
Copy code

5. const can only accept static scalars, while define can use any expression. For example:

  1. const BIT_5 = 1 << 5; // invalid
  2. but
  3. define('BIT_5', 1 << 5); // valid
Copy code

6, const Always case-sensitive, however define() can define case-insensitive constants via the third argument. For example:

  1. define('FOO', 'BAR', true);
  2. echo FOO; // BAR
  3. echo foo; // BAR
Copy code

From the above example, we get, const is simple and easy to read. It is a language structure in itself, while define is a method. Defining with const is much faster than define at compile time. As for which one to use, it depends on your own needs.



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