Welcome to my series on every PHP keyword and its usage. Today’s item: const.

This keyword allows you to define a constant (an immutable value, can only be defined once) globally or for a specific class.

Values that can be placed into an expression are limited to:

  • Any scalar literal, e.g. true, 7, "green".
  • Any existing constant.
  • An array literal containing any of the above, e.g. [1, 2, 3].
  • An expression made up of any of the above, e.g. 7 + 4 or "hello" . " world".

Note:

  • Variables and function calls cannot be assigned to a constant.
  • A global const statement cannot be used from within any control block (if statement, for loop, etc.) or function.
  • A class level const statement can only be used in the root of the class, and not from within method.

As an alternative, one can define a global constant using the define() method, which accepts variables and function calls, as long as they return a scalar value, a resource or an array containing either.

The define() method can be used from anywhere, including control blocks, functions and methods. This is likely to introduce needless complexity into your code, so it’s best to use const when possible.

Usage

Global constants

1
2
3
4
5
6
7
<?php
// By standard programming convention, constants are labelled with all caps
const PRIMARY_COLOUR = "green";
const SECONDARY_COLOUR = "red";
const BOTH_COLOURS = PRIMARY_COLOUR . " and " . SECONDARY_COLOUR;

echo BOTH_COLOURS;

Class constants

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
interface ColourInterface
{
	const ORANGE = "orange";
}

class Colour implements ColourInterface
{
	const BLUE = "blue";
	
	// Constants can optionally have visibility, they are public by default
	protected const GREEN = "green";
	
	// self::BLUE can be used here, but static::BLUE cannot. 
	const PRIMARY_BLUE = self::BLUE;
	
	public function output()
	{
		// The value that is defined in the current class
		echo self::PRIMARY_BLUE;
		
		// The value that is defined in the calling class, which may be this
		// class, or a child class.
		echo static::PRIMARY_BLUE;
		
		// Constants from parent classes or interfaces will be inherited by
		// the extending/implementing class
		echo self::ORANGE;
	}
}

// Constants can be called from outside the class, as long as the constants are public
echo Colour::BLUE;
echo ColourInterface::ORANGE;