PHP7 Class Constant

Class constant are the constant properties declared within the class. It is like a variable, but without a dollar sign($) prefix that holds some value and remain unchangeable once set. A constant property is declared with the keyword 'const'. Class constants are always case sensitive. When we declare a constant within a class, assign a value, after that, the constant is accessible within any scope of the class and constant value will never be changed.

Example

<?php
class Corporate {
    const BRANCH = 'India';
    const COMPANY = 'eTp Company.';
    public function welcome($empname) {
        $msg = 'Hello '.$empname.', Welcome to the '.Corporate::COMPANY;
        return $msg;
    }
}
echo Corporate::BRANCH;
echo '<br/>';
echo Corporate::COMPANY;
?>

Output

India
eTp Company.

In the above example, you can see that class constant is declared with the keyword 'const' and no access specifier. The constant property is called by using the class name followed by double colon operator (::) and the constant name.







Read more articles


General Knowledge



Learn Popular Language