PHP Static Methods & Properties

In the previous chapters, we have accessed the properties and methods by creating an instance of a class. This is also possible to access the properties and methods without instantiating a class. For this, the properties and methods must be declared as static. This process saves us from instantiating an object, or we can access the methods and properties without storing an object in a global variable.

Scope Resolution Operator(::)

In the given example, the static property and method are preceeded with the keyword 'static'. To access the static property and method, the class name is used with the scope resolution operator(::).


<?php
    class Person {
        static $days = 30;
        static function name($employee) {
            return 'Employee Name: '.$employee;
        }
    }
    echo Person::$days;
    echo '<br/>';
    echo Person::name('John');
?>

Use of 'self' and 'parent' keywords

In inheritance, the child class can access the static properties and methods of the parent class. For this 'self' and 'parent' keywords are used in place of 'this' keyword. To access the parent class properties and methods, the child class can use the parent keyword and to access the properties and methods within the same class, self keyword is used in place of 'this'.



Example


<?php
    class Person {
        static public $days = 30;
        static function name($employee) {
            return 'Employee Name: '.$employee;
        }
        static function attend(){
            return 'Number of present days : '.self::$days;
        }
    }
    class Employee extends Person {
        public function salary($basic){
            $salary = parent::$days * $basic;
            return 'Current Salary: Rs.'.$salary;
        }
    }
    echo Employee::attend();
    echo '<br/>';
    echo Employee::salary(500);
?>

Output

Number of present days : 30
Current Salary: Rs.15000




Read more articles


General Knowledge



Learn Popular Language