PHP Constant

PHP Constant
  • PHP constants is like variables and identifier for a simple value.
  • once constant are defined they cannot be changed or undefined.
  • A constant value cannot change during the execution of the script.
  • A constant is case-sensitive, A valid constant name starts with a letter or underscore.
PHP constant: define()
  • create a constant Use the define() function.

define(name, value, case-insensitive)

  1. name: It specifies the constant name.
  2. value: It specifies the constant value.
  3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case sensitive by default.

Example : constant with case-sensitive name

<!DOCTYPE html>
<html>
<body>
<?php
define("Hello", "Welcome to phpcoderspoint.com");
echo Hello;
?>
</body>
</html>

Example : constant with case-insensitive name

<!DOCTYPE html>
<html>
<body>
<?php
define("HELLO", "Welcome to phpcoderspoint.com", true);
echo hello;
echo "<br/>";
echo Hello;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
define("HELLO","Welcome to phpcoderspoint.com",false);
define("HELLO","Welcome to phpcoderspoint.com",false);
echo HELLO;
echo hello;
?>
</body>
</html>

Output:

Welcome to phpcoderspoint.com
Warning: Use of undefined constant hello - assumed 'hello' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\example\p7.php on line 9 hello

php constant work with array

<!DOCTYPE html>
<html>
<body>

<?php
define("radiation", ["alpha", "beta", "gamma"]);
echo radiation[1];
?>

</body>
</html>


php constant are automatically global can be use in anyeare entire script.

<!DOCTYPE html>
<html>
<body>

<?php
define("hello", "Welcome to PHP Coders Point");
function welcome() {
echo hello;
}
welcome();
?>

</body>
</html>
PHP Magic Constants
  • PHP magic constants are the predefined constants in PHP which get changed on the basis of their use.
  • They start with a double underscore (__) and ends with a double underscore(__). Some magic constant is given below.
  • # Name Example
    1 __LINE__ The current line number of the file.
    2 __FILE__ The full path and filename of the file. If used inside an include,the name of the included file is returned
    3 __FUNCTION__ The function name. This constant returns the function name as it was declared (case-sensitive)
    4 __CLASS__ The class name. This constant returns the class name as it was declared (case-sensitive)
    5 __METHOD__ The class method name. The method name is returned as it was declared (case-sensitive)