Constants in php

constants in php


A constant is an identifier for a simple value. The value cannot change during the execution of the script. A constant is case-sensitive by default.

The name of a constant follows the same rules –
  1. A valid constant name starts with a letter or underscore.
  2. Constants are automatically global across the entire script.


Create constant –
For create a constant, use the define() function.


Syntax –
            define(name, value, case-insensitive – true or false);
           

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 1 - The example below create a constant valid or invalid constant name

<?php

     // Valid constant name
     define("Cyber",     "It’s cyber science."); 

     // Invalid constant name
     define("2Cyber",    " It’s cyber science.");

     // This is valid, but should be avoided
     define("__Cyber__", "Welcome in cyber science."); 

?>


Constants are Global

Constants are automatically global across the entire script.


Example – In this example use a constant inside a function, even if it is outside the function.

<?php

     define("Cyber", "Welcome to www.cyberteak.com");

     function myFun()
     {
         echo Cyber;
     }

     myFun();

?>


Post a Comment

1 Comments