DEV Community

Cover image for PHP Static Methods & Properties
Samuel K.M
Samuel K.M

Posted on • Updated on

PHP Static Methods & Properties

Static Methods

Static methods can be called directly - without creating an instance of the class first.
Static methods are declared with the static keyword:

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}
// Call static method
greeting::welcome();
?>
Enter fullscreen mode Exit fullscreen mode

A static method can be accessed from a method in the same class using the self keyword and double colon (::):

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

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

new greeting();
?>
Enter fullscreen mode Exit fullscreen mode

Static methods can also be called from methods in other classes. To do this, the static method should be public:

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

class SomeOtherClass {
  public function message() {
    greeting::welcome();
  }
}
?>
Enter fullscreen mode Exit fullscreen mode

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

<?php
class Name{
  protected static function getName() {
    return "Bazeng";
  }
}

class SayName extends Name {
  public $name;
  public function __construct() {
    $this->name= parent::getName();
  }
}

$name= new SayName;
echo $name ->name;
?>
Enter fullscreen mode Exit fullscreen mode
Static properties

Static properties are declared with the static keyword they can be called directly - without creating an instance of a class.Example:

<?php
class Person{
   public static $name = "Bazeng";
 }
echo Person::$name;
Enter fullscreen mode Exit fullscreen mode

To access a static property in a method in same class use self

<?php
class Person{
   public static $name = "Bazeng";
   public function sayName(){
     echo self::$name;
   }
 }

 $person = new Person();
 $person->sayName();

Enter fullscreen mode Exit fullscreen mode

To access a static property in a method in a parent class use parent

<?php
class Person{
   public static $name = "Bazeng";

 }
class SayName extends Person{
   public function __construct(){
    echo parent::$name;
   }
} 

$person = new SayName();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)