constants in php

constants in php

A constant in PHP is defined or declared by using define() function or by using the const keyword outside a class definition if you are using PHP 5.3.0. or a later version.

If you define a constant one time, you can never change it or undefine it again.
your constants can only contain boolean, integer, float and string (So called Scalar Data) . Global constants in PHP is assigned through the define() function

Example ⇓ Global Constants

<!DOCTYPE html>
 <html>
   <body>
     <?php
    define("CONSTANT", "Hello WebWideTutor!");
    echo CONSTANT;
    ?>
    </body>
 </html>
Output: Hello WebWideTutor!

Declaring Constants in a Class

In Object-oriented Programming PHP there is way to assign constants within a class. Like static properties, constants can be accessed directly through the class or within object methods using the self notation.
If a constant is defined, its value cannot be changed again, constants are defined only once.

Example ⇓ Constants in OOP PHP
To define a constant in a class,use the keyword const

    
<!DOCTYPE html>
 <html>
   <body>
     <?php
    class commissionRate {
        const GRADE_ONE = 0.1; 
        const GRADE_TWO = 0.05; 
        const GRADE_THREE = 0.05; 
    }
    //Accessing constants directly by using self nation (::) sign
    echo commissionRate::GRADE_ONE;
    ?>
    </body>
 </html>
Output: 0.1