Constants are like a variable, except that their value never changes during execution once defined.



  • The constant value is immutable.
  • Constant within a script is accessible to any area; however, they can be scalar values.
  • Constant names are case-sensitive, and they also follow the same naming requirements like variables, except the leading $.
  • It is considered best practice to define constants using only upper-case names.

Constant Definition in PHP

PHP define() function defines a constant.

Syntax:

 bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )
Parameters Description
name The name of the constant.
value The value of the constant; only scalar and null values are allowed. Scalar values are an integer, float, string or Boolean values.
case_insensitive If set to TRUE, the constant will be defined case-insensitive.

Example:

<?php 
    define("EMAIL", "[email protected]"); // Valid constant name
    echo EMAIL; // Displays "[email protected]"

    define("myCon", true);
    if (myCon) { } // Evaluates to true

    define("ONECONSTANT", "some value"); // Invalid constant name
    
    define("CONSTANT", "Hello world.");
    echo CONSTANT; // outputs "Hello world."
    echo Constant; // outputs "Constant" and issues a notice.
    
    define("GREETING", "Hello world.", true);
    echo GREETING; // outputs "Hello world."
    echo Greeting; // outputs "Hello world."
?> 

How to create and use PHP constants

String Concatenation in PHP

String Concatenation is a process of adding two strings. We can echo more than one variable or constant on a line using a concatenation operator ('.'), e.g.

<?php 
    $like = "I like php";
    $num = 7;
    echo $like . $num;

    echo "<p>";
    echo $like . " " . $num;
    echo "</p>";

    echo "My favorite php version is $num";
?>


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram