×
☰ See All Chapters

PHP Static Members

Static members declared with the static keyword in a class. Static variables should be declared outside any block, means should not be inside any functions, but should just inside class.

class Employee {

    public static $name;

   

    public static function pritnName () {

    }

}

Visibility is similar to non-static members. However, most static members are declared public since they must be available for users of the class.

To access static members outside the class, it is not necessary to create the object for class. There would only be one copy of each static member per class, regardless of how many objects are created from it.

Syntax to access static members

To access the static members outside the class it is not necessary to create the object for class. Below is the syntax to access static members.

ClassName::memberName;

Inside same class static members are accessed using self keyword.

self::memberName;

Inside subclass static members are accessed using parent keyword.

parent::memberName;

Static Members Example

<?php

class Employee {

    public static $name;

   

    public static function pritnName () {

        echo self::$name;

    }

}

 

class Developer extends Employee {

    public static function printDeveloperName () {

        echo parent::$name;

    }

}

 

//Create any number of objects for class, there will be only one copy of static members for entire application

$developer1 = new Developer();

$developer2 = new Developer();

$employee1 = new Employee();

$employee2 = new Employee();

 

Employee::$name = "Manu Manjunatha";

Employee::pritnName(); //Prints Manu Manjunatha

Developer::printDeveloperName(); //Prints Manu Manjunatha

 

?>

 


All Chapters
Author