static

The keyword static is used to make class members available at all times throughout a script, without the need for instantiating an object.

 

  • Because static methods are callable without an instance of an object being created, the pseudo-variable $this is not available inside a static method
    • instead the keyword self should be used e.g. return self::$myvar;
  • Static properties cannot be accessed through the object using the arrow operator ->
  • Static methods cannot access normal methods (those not declared static) since they belonging to an object, and not the class

 

Properties declared as static within a class mean that just one version of that property is used by all objects of that class. This could be useful for incrementing say a counter to keep a tally of the number of objects instantiated.

 

When a method is declared static it enables the method to be called like any other function.

 

In order to utilise static members from outside the class, the class name and the :: scope resolution operator must be used so that the correct member can be identified and used.

 

Syntax:

ClassName::member;

 

In this example a value has been assigned to the class's static $name property. This is called using self::$name within the class's static greet() function. To access the members from outside the class scope the :: scope resolution operator is used, as can be seen on lines 11 & 12:

Save & refresh browser:

Norman Fisher-Jones
Hi Norman Fisher-Jones

Leave a Reply