Introduction

PHP can create static methods in much the same way as static properties.

To make a method static, add the static keyword before the function keyword in the method definition:

class MyClass {
  public static function staticMethod() {
    // (do stuff here)
  }
}

To call a static method, use the following format:

MyClass::staticMethod();

static methods are useful to add some functionality that's related to a class, but that doesn't need to work with an actual object created from the class.

Here's a simple example:

Demo

<?php
class Truck {/*from w  w w .  java2  s. co m*/

    public static function calcMpg($miles, $gallons) {
              return ($miles / $gallons);
    }
}

echo Truck::calcMpg(168, 6); // Displays"28"
?>

Result

The calcMpg() method take two arguments - miles traveled and gallons of fuel used - and returns the calculated miles per gallon.

Notice that the calling code doesn't need to create a Truck object to use calcMpg().

Related Topic