Menu

Static Keyword in PHP

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).

1. Static Property

class Static_Class 
{
  // Static property
  public static $static_prop = 'value';
  // method
  public function sc_function() {
    return self::$static_prop;
  }
}

// Print the static property out
echo Static_Class::$static_prop;
// New Instance of Static_Class
$sc = new Static_Class();
echo $sc->static_prop; // Undefined "Property" static_prop
echo $sc->sc_function(); // The result same as Static_Class::$static_prop

 

2. Static Method

class Static_Class
{
  // Static Method
  public static function sc_function() {
    return 'You did it!';
  }
}

// Call the method
echo Static_Class::sc_function(); // You did it!

There is a frequently asked question: when to use self and $this? You can find a quite great explanation here: http://stackoverflow.com/questions/151969/when-to-use-self-vs-this

The original PHP Language Reference is here: http://php.net/manual/en/language.oop5.static.php

Have something on your mind?