PHP Constants

PHP Constants

PHP constants are name or identifier that can't be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways.

  • Using define( ) function
  • Using const keyword
  • Numbers with decimal points are classified as floating points.
  • True or false values are classified as Boolean.

Constants are similar to the variable except once they defined, they can never be undefined or changed. They remain constant across the entire program. PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only. Conventionally, PHP constants should be defined in uppercase letters.

Create a PHP Constant

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

Syntax

define(name, value, case-insensitive)

  • 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
  •       
                            <?php
    define("GREETING", "Welcome to W3Schools.com!");
    echo GREETING;
    ?>
                        

    PHP Constant Arrays

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

    In the following example $x is an integer. The PHP var_dump() function returns the data type and value:

  •       
                            <?php
    define("cars", [
      "Alfa Romeo",
      "BMW",
      "Toyota"
    ]);
    echo cars[0];
    ?>
                        

    Constants are Global

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

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

  •       
                            <?php
    define("GREETING", "Welcome to W3Schools.com!");
    
    function myTest() {
        echo GREETING;
    }
        
    myTest();
    ?>
    

    Dess App

    DessApp is an Integrated E-learning Education, Interactive and User-friendly features, smarter options and redefining your school costs effectively and efficiently.

    View
    1 1