PHP constants are identifier for a simple value. The possible datatypes of constants are boolean, integer, double, and string. Once we defined the constant, we cannot change the value of constant and cannot unset the constant.
Characteristics of constant:
- constant is case sensitive by default
- The name of a constant is uppercase
- A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores
- Variables start with $, whereas constants are not start with $
- Like global variable constant will be accessible from anywhere in the programming
- You can get the value of constant by specifying its name
1 |
Syntax: bool define (string $name, mixed $value [, bool $case_insensitive = false]) |
$name – Name of the constant variable
$value – Value of the constant variable
$case_insensitive – The default value is FALSE. The defined constant variable should be accessible by as it is, if you access the variable by using non case sensitive then it issues a notice. For Example: Consider following example.
Example
1 2 3 4 5 6 7 |
define("PHP_SCRIPT", "Hello world."); echo PHP_SCRIPT; // outputs "Hello world." echo Php_script; // Notice: Use of undefined constant Php_script. define("PHP_SCRIPT", "Hello world.", true); echo PHP_SCRIPT; // outputs "Hello world." echo Php_script; // outputs "Hello world." |
If you are using PHP version greater than or equal to 7.0 then it is possible to create constant variable as array().
Example
1 2 3 4 5 6 7 |
// Works as of PHP 7 define('ANIMALS', array( 'dog', 'cat', 'bird' )); echo ANIMALS[1]; // outputs "cat" |
Class Constants:
If you want to create constant variable for procedural PHP coding then you can create PHP constant variable by using define() function. Otherwise you can create the constant variable by using const keyword inside the class.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php class ConstantExample { const CONSTANT = 'value unchanged'; function constantInFunction() { echo self::CONSTANT; // Constant variable is accessible inside function of Class } } echo ConstantExample::CONSTANT; // Constant variable is accessible outside of Class $classname = "ConstantExample"; echo $classname::CONSTANT; // As of PHP 5.3.0, Constant variable is accessible by Class variable $classObj = new ConstantExample(); echo $classObj::CONSTANT."\n"; // As of PHP 5.3.0, Constant variable is accessible by Class object ?> |
Click the below button to see the demo.
Demo