Industrial Training




PHP Constants


Constants are like variables except that once they are defined they cannot be changed or undefined.


A constant is an identifier (name) for a simple value. The value cannot be changed during the script.


A valid constant name starts with a letter or underscore (no $ sign before the constant name).


Note: Unlike variables, constants are automatically global across the entire script.


Create a PHP Constant


To create a constant, use the define() function.


Syntax
define(name, value, case-insensitive)

Parameters:


  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

Example

Create a constant with a case-sensitive name:


< ?php
class="phpnumbercolor" style="color:red"> define(class="phpstringcolor" style="color:brown">"GREETING", class="phpstringcolor" style="color:brown">"Welcome to W3Schools.com!");
class="phpkeywordcolor" style="color:mediumblue">echo GREETING;
class="phptagcolor" style="color:red">?>

Example

Create a constant with a case-insensitive name:


< ?php
class="phpnumbercolor" style="color:red"> define(class="phpstringcolor" style="color:brown">"GREETING", class="phpstringcolor" style="color:brown">"Welcome to W3Schools.com!", true);
class="phpkeywordcolor" style="color:mediumblue">echo greeting;
class="phptagcolor" style="color:red">?>

PHP Constant Arrays


In PHP7, you can create an Array constant using the define() function.


Example

Create an Array constant:


< ?php
class="phpnumbercolor" style="color:red"> define(class="phpstringcolor" style="color:brown">"cars", [
  class="phpstringcolor" style="color:brown">"Alfa Romeo",
  class="phpnumbercolor" style="color:red"> class="phpstringcolor" style="color:brown">"BMW",
  class="phpstringcolor" style="color:brown">"Toyota"
]);
class="phpkeywordcolor" style="color:mediumblue">echo cars[class="phpnumbercolor" style="color:red">0];
class="phptagcolor" style="color:red">?>

Constants are Global


Constants are automatically global and can be used across the entire script.


Example

This example uses a constant inside a function, even if it is defined outside the function:


< ?php
define(class="phpstringcolor" style="color:brown">"GREETING", class="phpstringcolor" style="color:brown">"Welcome to W3Schools.com!");

class="phpkeywordcolor" style="color:mediumblue">function myTest() {
class="phpnumbercolor" style="color:red">   class="phpkeywordcolor" style="color:mediumblue">echo GREETING;
}
 
myTest();
class="phpnumbercolor" style="color:red"> class="phptagcolor" style="color:red">?>




Hi I am Pluto.