Showing posts with label constant. Show all posts
Showing posts with label constant. Show all posts

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

Tuesday, 30 March 2021

Php: Constants

Constants are used to define immutable variables. Suppose if you have aa scenario such that where the value of variable shouldn’t change throughout application life cycle, you should define that variable as constant.

 

How to define a constant variable?

Constants are defined using ‘define’ function.

 

Example

define("__PI__", 3.14);

 

__PI__ is the name of the constant and it has value 3.14.

 

Constant naming conventions

a.   Constant name must starts with a letter or underscore, followed by any number of letters, numbers or underscores with one exception.

b.   By convention, constant variable name is always uppercase.

 

constant_demo.php

#!/usr/bin/php

<?php
    
   define("__PI__", 3.14);
   
   echo __PI__;
?>

Output

$./constant_demo.php 

3.14


Note

$ prefix is not required for constant names.



 

  

Previous                                                    Next                                                    Home