MOCKSTACKS
EN
Questions And Answers

More Tutorials









PHP Constants

Constants are created using the const statement or the define function. The convention is to use UPPERCASE letters for constant names.


const PI = 3.14; // float
define("EARTH_IS_FLAT", false); // boolean
const "UNKNOWN" = null; // null
define("APP_ENV", "dev"); // string
const MAX_SESSION_TIME = 60 * 60; // integer, using (scalar) expressions is ok
const APP_LANGUAGES = ["de", "en"]; // arrays
define("BETTER_APP_LANGUAGES", ["lu", "de"]); // arrays

Define constant using another constant

if you have one constant you can define another one based on it:


const TAU = PI * 2;
define("EARTH_IS_ROUND", !EARTH_IS_FLAT);
define("MORE_UNKNOWN", UNKNOWN);
define("APP_ENV_UPPERCASE", strtoupper(APP_ENV)); // string manipulation is ok too
// the above example (a function call) does not work with const:
// const TIME = time(); # fails with a fatal error! Not a constant scalar expression
define("MAX_SESSION_TIME_IN_MINUTES", MAX_SESSION_TIME / 60);
const APP_FUTURE_LANGUAGES = [-1 => "es"] + APP_LANGUAGES; // array manipulations
define("APP_BETTER_FUTURE_LANGUAGES", array_merge(["fr"], APP_BETTER_LANGUAGES));

Reserved constants

Some constant names are reserved by PHP and cannot be redefined. All these examples will fail:


define("true", false); // internal constant
define("false", true); // internal constant
define("CURLOPT_AUTOREFERER", "something"); // will fail if curl extension is loaded

Conditional defines

If you have several files where you may define the same variable (for example, your main config then your local config) then following syntax may help avoiding conflicts:


defined("PI") || define("PI", 3.1415); // "define PI if it's not yet defined"

const vs define

define is a runtime expression while const a compile time one.
Thus define allows for dynamic values (i.e. function calls, variables etc.) and even dynamic names and conditional
definition. It however is always defining relative to the root namespace.

const is static (as in allows only operations with other constants, scalars or arrays, and only a restricted set of them, the so called constant scalar expressions, i.e. arithmetic, logical and comparison operators as well as array dereferencing), but are automatically namespace prefixed with the currently active namespace.

const only supports other constants and scalars as values, and no operations.


Class Constants

Constants can be defined inside classes using a const keyword.


class Foo {
 const BAR_TYPE = "bar";
 // reference from inside the class using self::
 public function myMethod() {
 return self::BAR_TYPE;
 }
}
// reference from outside the class using <ClassName>::
echo Foo::BAR_TYPE;

This is useful to store types of items.


<?php
class Logger {
 const LEVEL_INFO = 1;
 const LEVEL_WARNING = 2;
 const LEVEL_ERROR = 3;
 // we can even assign the constant as a default value
 public function log($message, $level = self::LEVEL_INFO) {
 echo "Message level " . $level . ": " . $message;
 }
}
$logger = new Logger();
$logger->log("Info"); // Using default value
$logger->log("Warning", $logger::LEVEL_WARNING); // Using var
$logger->log("Error", Logger::LEVEL_ERROR); // using class

Using constants

To use the constant simply use its name:


if (EARTH_IS_FLAT) {
 print "Earth is flat";
}
print APP_ENV_UPPERCASE;

or if you don't know the name of the constant in advance, use the constant function:


// this code is equivalent to the above code
$const1 = "EARTH_IS_FLAT";
$const2 = "APP_ENV_UPPERCASE";
if (constant($const1)) {
 print "Earth is flat";
}
print constant($const2);

Constant arrays

Arrays can be used as plain constants and class constants from version PHP 5.6 onwards:


Class constant example


class Answer {
 const C = [2,4];
}
print Answer::C[1] . Answer::C[0];

Output

42

Plain constant example


const ANSWER = [2,4];
print ANSWER[1] . ANSWER[0];

Output

42

Also from version PHP 7.0 this functionality was ported to the define function for plain constants.


define('VALUES', [2, 3]);
define('MY_ARRAY', [
 1,
 VALUES,
]);
print MY_ARRAY[1][1];

Output

3


Conclusion

In this page (written and validated by ) you learned about PHP Constants . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Comments.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.