PHP Constants
A constant holds a value much as a variable does, with one key difference: after you define it, you can neither change it nor undefine it.
PHP gives you two ways to create one, the define() function and the const keyword.
Names follow a simple rule: begin with a letter or an underscore, and leave out the $ sign that variables use.
PHP define() Function
define() creates its constant at run-time.
The constant always lands in the global scope, even when define() is called inside a conditional block (if/else, loops, functions). Class constants, however, are out of reach for this function.
It takes two parameters:
- CONSTANT_NAME - what the constant is called (case-sensitive)
- value - what the constant holds
Create a constant with define()
Here define() creates a constant called "GREETING", and echo prints it. Note the missing $ sign:
Output: PHP script
<?php
define("GREETING", "Welcome to PromptCookbook!");
echo GREETING;
?>
Constant inside a function
The constant is created inside myTest(), yet the code outside the function can still print it:
Output: PHP script
<?php
function myTest() {
define("GREETING", "Welcome to PromptCookbook!");
}
myTest();
echo GREETING;
?>
define() syntax
This is the general form of a define() call:
<?php
define(CONSTANT_NAME, value);
?>
PHP const Keyword
With const, the constant is created at compile-time instead.
That timing is why it has to sit at the top-level scope. You can't use const this way inside functions, loops, if/else statements or try/catch blocks.
Unlike define(), it also works for class constants.
Names are case-sensitive here as well.
Create a constant with const
The same "GREETING" constant, this time made with const:
Output: PHP script
<?php
const GREETING = "Welcome to PromptCookbook!";
echo GREETING;
?>
const syntax
This is the general form of a const declaration:
<?php
const CONSTANT_NAME = value;
?>
PHP Array Constants
A constant doesn't have to hold a single value. Both define() and const accept arrays too.
Create array constants
One array constant comes from each approach, and elements are read by index as in any array:
Output: PHP script
<?php
// Using define()
define("CARS", array("Volvo", "BMW", "Toyota"));
echo CARS[0];
// Using const
const ANIMALS = array("Cat", "Dog", "Horse");
echo ANIMALS[1];
?>