How to define constant in PHP 7

How to use Constants in php 7

How to define constant in PHP 7

How to define constant in PHP 7

What is Constants In PHP

In Object Oriented Programming we can define constants. Mainly when you want to use some variables with some values and you want to make sure the value to that variable never changes then you use constant. Once value is defined to constant it cannot be changed.

Here is how constant work in PHP

Here is a example

class User{

    // Class Constants with visibility

    public const EMPLOYEE_ID = 23423;
    protected const GENDER = 'Male';
    private const HEIGHT='5,11';
    // Normal Variable
    public $age = '23';

    //Function calling constant with in class
    public function displayId(){
        //Calling constant using scope resolution operator
        return self::EMPLOYEE_ID;

$user = new User();

// Displaying variable value outputs 23
echo $user->age = 23;

// Displaying constant outside class using scope resolution operator displays id

echo $user::EMPLOYEE_ID;

// This will return error as we need to use scope resolution operator for constant

echo $user->EMPLOYEE_ID;

// This will return an error as we cannot change the value of constant
$user->EMPLOYEE_ID = 232;