Categories
PHP

Constants

A constant is a variable with a value that cannot be changed by the script. Therefore, such a value must be assigned at the same time that the constant is created. Constants may not be redefined or undefined once they have been set.

PHP provides two methods for creating constants: the const modifier and the define() function. Prior to PHP 5.3, constants associate a name with a simple, scalar value. For example, the Boolean values true and false are constants associated with the values 1 and nothing, respectively.

It’s also common to declare constants in a script. Consider this example constant declaration:

define("pi", 3.14159);
// This outputs 3.14159
echo pi;

The third parameter of define is optional and indicates whether the constant name is case sensitive or not. The default behavior is case-sensitive, if set to TRUE, the constant will be defined case-insensitive:

define("pi", 3.14159, true);
// This outputs 3.14159
echo PI;

Note: Defining case-insensitive constants is deprecated as of PHP 7.3.0.

Constants aren’t preceded by a $ character; they can’t be changed once they have been defined; they can be accessed anywhere in a script, regardless of where they are declared; and they can only be simple, scalar values.

Constants are useful because they allow parameters internal to the script to be grouped. When one parameter changes, for example, if you define a new maximum number of lines per web page, you can alter this constant parameter in only one place and not throughout the code.

Following is a brief version history of CONSTANTS in PHP:

  • As of PHP 5.3, you can use the const keyword to define global constants (previously, const keyword is used to create class constants).
  • As of PHP 5.6, it is possible to define an array constant by using const keyword.
  • As of PHP 7, array constants can also be defined using define() function.

const

The const keyword is used to create class constants. Unlike regular properties (variables), class constants do not have an access level specified because they are always publicly visible:

class Circle {
 const PI = 3.14159;
}

Constants must be assigned a value when they are created. A constant may only be initialized with a constant value, and not with an expression. Class constants are referenced in the same way as static properties:

// 3.14159
echo Circle::PI;

As of PHP 5.3, const can be used to create global constants. Such a constant is defined in the global scope and can be accessed anywhere in the script:

const PI = 3.14159;

//3.14159
echo PI;

The define() function

The define function can create both global and local constants, but not class constants. The first argument to this function is the constant’s name and the second is its value:

define(PI, 3.14159);

Just like constants created with const, define constants are used without the dollar sign and their value cannot be modified.

The defined() function

To check whether a constant already exists, the defined() function can be used. This function works for constants created with const or define():

if (!defined(PI)) {
 echo 'PI not defined';
}

PHP 7 made it possible to create constant arrays using the define() function. Support for constant arrays created with const has existed since PHP 5.6.

Constant arrays

Prior to PHP 7, constants defined with define() could only contain scalar expressions, but not arrays. As of PHP 5.6, it is possible to define an array constant by using const keyword, and as of PHP 7, array constants can also be defined using define():

// the define() example
define(ARR, [
 'string' => 'some text',
 'number' => 123
]);
echo ARR['string']; // some text
echo ARR['number']; // 123

// the class const example
class Temp {
 const ARR = [
  'string' => 'some text',
  'number' => 123
 ];
}
echo Temp::ARR['string']; // some text
echo Temp::ARR['number']; // 123

// the global const example
const ARR = [
 'string' => 'some text',
 'number' => 123
];
echo ARR['string']; // some text
echo ARR['number']; // 123

define() vs const

As of PHP 5.3 there are two ways to define constants: Either using the const keyword or using the define() function:

const PI = 3.14159;

//OR
define(PI, 3.14159);

The fundamental difference between those two ways is that const defines constants at compile-time, whereas define() defines them at run time.

const cannot be used to conditionally define constants. To define a global constant, it has to be used in the outermost scope, for example:

if (...) {
 const PI = 3.14159; //invalid
 
 define(PI, 3.14159); //valid
}

const defines a constant in the current namespace, while define() has to be passed the full namespace name:

namespace A\NAME\SPACE;
// To define the constant A\NAME\SPACE\PI:
const PI = 3.14159;
define('A\NAME\SPACE\PI', 3.14159);

const can use within a class or interface to define a class constant or interface constant. define() cannot be used for this purpose:

// valid
class Circle {
 const PI = 3.14159;
}

// invalid
class Wheel {
 define(PI, 3.14159);
}

Predefined Constants – the magic constants

PHP comes ready-made with dozens of predefined constants that you generally will be unlikely to use as a beginner to PHP. The names of the magic constants always have two underscores at the beginning and two at the end, so that you won’t accidentally try to name one of your own constants with a name that is already taken. They are detailed in the following listing:

  • __LINE__
    The current line number of the file.
  • __FILE__
    The full path and filename of the file. If used inside an include, the name of the included file is returned.
  • __DIR__
    The directory of the file. If used inside an include, the directory of the included file is returned. The returned directory name does not have a trailing slash unless it is the root directory.
  • __FUNCTION__
    The function name. Returns the function name as it was declared.
  • __CLASS__
    The class name. Returns the class name as it was declared.
  • __METHOD__
    The class method name. The method name is returned as it was declared.
  • __NAMESPACE__
    The name of the current namespace. This constant is defined at compile time.
  • __TRAIT__
    The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
  • ClassName::class
    You can get a string containing the fully qualified name of the ClassName class. This is particularly useful with namespaced classes.

One handy use of these variables is for debugging purposes, when you need to insert a line of code to see whether the program flow reaches it:

echo "This is line " 
 . __LINE__ . " of file " . __FILE__;

This causes the current program line in the current file (including the path) being executed to be output to the web browser.


Getting Started with PHP:

  1. Introducing PHP
  2. PHP Development Environment
  3. Variable Assignment, Expressions, and Operators
  4. Delimiting Strings
  5. Variable Substitution
  6. Constants