PHP Static methods and Properties

What are the PHP Static methods and Properties and how to define them?

What are the Static methods and Properties in PHP OOP?

PHP OOP static methods and properties are special types of members of a class that you can access directly without creating objects of the class.


How to define the Static Methods and Properties in PHP?

The static keyword is used to define a static member (method/property) inside a PHP class.

Syntax of the Static members

static public $name = "John";
static public function funcName(){ ... }

Example of the Static members

You can access PHP static members by using the scope resolution operator (::) with the ClassName. like – MyClass::$name, MyClass::sayHello().

<?php
class MyClass{
    static public $name = "John\n";
    static public function sayHello(){
        echo "Hello World!";
    }
}

// Accessing the static members
echo MyClass::$name;
MyClass::sayHello();
John
Hello World!

Accessing the static members inside the class

A class can access its own static methods and properties with the help of the self:: keyword.

<?php
class MyClass{
    static private $name = "Mark\n";
    static private function sayHello($n){
        echo "Hello $n";
    }

    public function a(){
        echo self::$name;
        self::sayHello("Ortiz");
    }
}

$obj = new MyClass();

$obj->a();
Mark
Hello Ortiz

Accessing the parent class static members inside a derived class

The self:: keyword can’t access static members of the parent class. You have to use the parent:: keyword or you can use the class name (ClassName::) to access the parent class’s static members.

<?php
class Abc{
    static protected $name = "Mark\n";
    static protected function sayHello($n){
        echo "Hello $n";
    }
}

class MyClass extends Abc{
    public function a(){
        echo parent::$name;
        // You can also do this
        echo Abc::$name;
        echo parent::sayHello("Baburao");
    }
}

$obj = new MyClass();
$obj->a();
Mark
Mark
Hello Baburao

How to override static members inside a derived class?

You can override the static members in the same way you override ordinary members. But, you have to use the static:: keyword to access the overridden members.

<?php
class Abc{
    static protected $name = "Mark\n";
    static protected function sayHello($n){
        echo "Hello $n";
    }
}

class MyClass extends Abc{
    // overriding the $name variable
    static protected $name = "Chaman Jhinga\n";
    
    public function a(){
        // You cannot do this
        echo parent::$name;
        // Accessing the overridden member
        echo static::$name;
        echo Abc::sayHello("Baburao");
    }
}

$obj = new MyClass();
$obj->a();
Mark
Chaman Jhinga
Hello Baburao