Spread the love

Static keyword are isolated, which means we can access the property of a class without creating a object/instance of class. static methods that are common to all the objects of the class. Hence, any logic which can be shared among multiple instances of a class should be inside the static functions. let’s have a quick example:

<?php
class NameOfClass {
  public static function myStaticMethod() {
    echo "Hello World!";
  }
}
?>

we can access a static method class name double colon(::) scope resolution operator, and the method name:

NameOfClass::myStaticMethod();

We can not access static method by creating an object

$classobject=new NameOfClass();
$classobject->myStaticMethod();

it will produce error, static member can not access as non-static member.

Let’s go more deep dive in

<?php
/* Use of static method in PHP */
  
class NormalA {
      
    public function test($var = "Hello World") {
        $this->var = $var;
        return $this->var;
    }
}
  
class NormalB {
    public static function test($var) {
        $var = "This is static";
        return $var;
    }
}
  
// Creating Object of class A
$obj = new NormalA();
  
echo $obj->test('This is non-static'); 
echo "\n";
echo NormalB::test('This is non-static'); 
  
?>

Output

This is non-static
This is static

Self keyword is used to access only static methods, we can’t access not static method using self. you can use $this to access the non static methods in a class

<?php 
class SelfClassName{

  public static function testself(){

  }
  public function test(){
     self::testself();  // we can access static function and properties in non static methods
     SelfClassName::testself(); //correct
  }
  public function test2(){
     $this->testself(); // wrong access, we can't access static properties as statically 
  } 
}

class childClass extends SelfClassName{

   public static function testself(){

   }

   public function test3(){
    parent::testself();
    self::testself(); 
   }

}

I hope it will clear all doubts.

Leave a Reply