Static Function in PHP

 STATIC FUNCTION 

  • Any method declared as static with the static keyword.
  • Accessible without the creation of an object.
  • Associated with the class, not an instance of the class.
  • Permitted to access only static methods and static variables.

Syntax

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

 A class can have both static and non-static methods. A static method can be accessed from a method in the same class using the self keyword and double colon (::):


Syntax

ClassName::staticMethod();

 

Example

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

// Call static method
greeting::welcome();

?>

Output:-

Hello World!

 

Example: WAP to display static function as counter.

<?php

/* Use static function as a counter */   

class solution {      

    static $count;      

    public static function getCount() {

        return self::$count++;

    }

 

solution::$count = 1;  

for($i = 0; $i < 5; ++$i) {

    echo 'The next value is: '. 

    solution::getCount() . "\n";

 

?>

Output:

The next value is: 1

The next value is: 2

The next value is: 3

The next value is: 4

The next value is: 5

 

Differences between the self and $this 

$this

self

Represents an instance of the class or object

Represents a class

Always begin with a dollar ($) sign

Never begin with a dollar($) sign

Is followed by the object operator (->)

Is followed by the :: operator

The property name after the object operator (->) does not have the dollar ($) sign, e.g., $this->property.

The static property name after the :: operator always has the dollar ($) sign.


Example

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }

  public function __construct() {
    self::welcome();
  }
}

new greeting();
?>

Output:-

Hello World!

 

Static methods can also be called from methods in other classes. For this static method should be public:

Example

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

class SomeOtherClass {
  public function message() {
    greeting::welcome();
  }
}
?>

 To call a static method from a child class, use the parent keyword inside the child class. The static method can be public or protected.

 Example:-

<?php
class d1 {
  protected static function g1() {
    return "cyber monk hindi";
  }
}

class d3 extends d1 {
  public $w;
  public function __construct() {
    $this->w = parent::g1();
  }
}

$d3 = new d3;
echo $d3 -> w;
?>

Output:-

cyber monk hindi  

Post a Comment

0 Comments