This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

7.11 PHP Static Methods

    • Static methods can be called directly - without creating an instance of the class first.
    • Static methods 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, double colon (::), and the method name:

    Syntax

    ClassName::staticMethod();

    Let's look at an example:

    Example 1: PHP Static Methods part 1
    <?php
    class greeting {
      public static function welcome() {
        echo "Hello World!";
      }
    }
    
    // Call static method
    greeting::welcome();
    ?>

    Example Explained

    Here, we declare a static method: welcome(). Then, we call the static method by using the class name, double colon (::), and the method name (without creating an instance of the class first).

    PHP - More on Static Methods

    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 (::):

    Example 2: PHP Static Methods part 2
    <?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. To do this, the static method should be public:

    Example 3: PHP Static Methods part 3
    <?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. Here, the static method can be public or protected.

    Example 4: PHP Static Methods part 4
    <?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;
    ?>
    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon

    Module 6 quiz