HomeCareerDifference between constant and define function in PHP

Difference between constant and define function in PHP

  1. const takes a plain constant name, whereas define() accepts any expression as name. This allows to do things like this:

for ($i = 0; $i < 32; ++$i)

{

    define(‘BIT_’ . $i, 1 << $i);

}

  1. const are always case sensitive, whereas define() allows you to define case insensitive constants by passing true as the third argument:
  2. Since PHP 5.6 const constants can also be arrays, while define() does not support arrays yet. However arrays will be supported for both cases in PHP 7.

const FOO = [1, 2, 3]; // valid in PHP 5.6

define(‘FOO’, [1, 2, 3]); // invalid in PHP 5.6, valid in PHP 7.0

  1. Consts cannot be defined from an expression. const FOO = 4 * 3; doesn’t work, but define(‘CONST’, 4 * 3);
  2. It is well known that PHP define() is slow when using a large number of constants.
  3. Finally, note that const can also be used within a class or interface to define a class constant or interface constant. define cannot be used for this purpose.
Saral Study
Saral Study
Saral Study staff mostly works for helpful articles and other posts which include student-related news, education-related news, updates, informative lists, etc.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Latest Blogs