Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Static Methods

PHP – Static Methods

Static methods can be called directly, without needing to create an instance of the class first. They are declared with the static keyword.

Syntax

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

To access a static method, use the class name followed by the double colon (::) and the method name.

Syntax

ClassName::staticMethod();

Here’s an example:

Example

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

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

Example Explained

In this example, we declare a static method called welcome(), which is then called using the class name followed by the double colon (::) and the method name, without needing to create an instance of the class first.

PHP – More on Static Methods

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

Example

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

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

new greeting();
?>

Static methods can also be called from methods in other classes, provided the static method is declared as public.

Example

<?php
class A {
  public static function welcome() {
    echo “Hello World!”;
  }
}

class B {
  public function message() {
    A::welcome();
  }
}

$obj = new B();
echo $obj -> message();
?>

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

<?php
class domain {
  protected static function getWebsiteName() {
    return “W3Schools.com”;
  }
}

class domainW3 extends domain {
  public $websiteName;
  public function __construct() {
    $this->websiteName = parent::getWebsiteName();
  }
}

$domainW3 = new domainW3;
echo $domainW3 -> websiteName;
?>