Friday, 21 May 2021

Php: Class level constants

 You can define a class level constant using ‘const’ keyword followed by variable name in capital letters.

 

Example

const ORGANIZATION_NAME = 'ABC Corp';

 

Can I apply access specifier or visibility modifier to class constants?

Yes

 

Example

public const ORGANIZATION_NAME = 'ABC Corp';

 

 

How to refer class constant from outside of the class?

Syntax

ClassName::variable_name

 

Example

Employee::ORGANIZATION_NAME;

 

How to refer the class constant within the class?

Syntax

self::variable_name

 

Example

self::ORGANIZATION_NAME;

 

class_constant_demo.php

#!/usr/bin/php

<?php

    class Employee{
        public const ORGANIZATION_NAME = 'ABC Corp';
        private static $total_employees = 100;

        public static function about_class(){
            $org_name = self::ORGANIZATION_NAME;
            $total_emps = self::$total_employees;

            echo "organization name : $org_name\n";
            echo "total employees : $total_emps\n";
        }

    }

    $org_name = Employee::ORGANIZATION_NAME;
    echo "organization name(outside of class) : $org_name\n";

    Employee::about_class();
   
?>

 

Output

$./class_constant_demo.php 

organization name(outside of class) : ABC Corp
organization name : ABC Corp
total employees : 100

 


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment