Sunday 16 May 2021

Php: Static properties

 

Static properties are associated with class not with an object.

 

How to define a static property?

Using ‘static’ keyword you can define a static property.

 

Syntax

static $variable_name;

 

Example

static $organization_name = 'ABC Corp';

static $total_employees = 100;

 

How to access static properties?

Syntax

ClassName::$name_of_the_property;

 

Example

Employee::$organization_name;

 

How to access the static properties inside the class?

Syntax

self::$name_of_the_property

 

Example

$org_name = self::$organization_name;

$total_emps = self::$total_employees;

 

Can I apply access specifiers/visibility modifiers to static properties?

Yes, you can do.

 

Example

public static $organization_name = 'ABC Corp';

private static $total_employees = 100;

 

Find the below working application.

 

static_properties_demo.php

#!/usr/bin/php

<?php

    class Employee{
        public static $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;
    //since total_employees is private, this will not run
    //$total_emp = Employee::$total_employees; 
   
    Employee::about_class();
   
?>

Output

$./static_properties_demo.php 

organization name : ABC Corp
total employees : 100

Note

a.   Static properties are not accessible via instance.

b.   You can’t access $this from static method.

c.    Private static properties are not accessible outside of the class.



Previous                                                    Next                                                    Home

No comments:

Post a Comment