PHP

Static Member Variables

For situations where you would like to associate some data with an entire class of objects, but the data is not fixed (in other words, constant), you can create member variables that are global to the entire class, not just specific instances. In PHP, these are called static member variables. They are declared by prefixing their declarations with the keyword static.

<?php
  class ABC
  {
    public static $x;
    // etc.
  }
?>

You would declare static member variables just like any other; you can specify a visibility modifier with it and assign it an initial value. For the previous example, class ABC, I have declared a static class variable called x that anybody can access and modify. Any instance of class ABC sees the same value if it asks for the value of x, and it does not have its own storage location for it.

Accessing the value of a static variable is similar to accessing for a class constant: You either use the type name (outside of or within the class) or the keyword self, both followed by the scope resolution operator (::) and the name of the static variable, starting with $. As a more interesting example, I can use a static member variable to count the number of instances of a class (such as my Product class) that have been created:

<?php
  class Product
  {
    private static $num_instances_created = 0;
    public function __construct
    (
      $in_prodid,
      $in_prodname,
      $in_proddesc,
      $in_price_pu,
      $in_location
    )
    {
      $this->id = $in_prodid;
      $this->name = $in_prodname;
      $this->desc = $in_proddesc;
      $this->price_per_unit = $in_price_pu;
      $this->location = $in_location;
      self::$num_instances_created++;
      echo "I've created " . self::$num_instances_created
           . " instances so far!<br/>\n";
    }
   }
?>

Unlike constants, static member variables can be declared at a scoping level other than public, and they are not read-only.

PHP remembers nothing between script invocations, including variable values. Static class variables are no exceptiontheir value is reset every time script execution restarts anew. The following script always prints out 10:

<?php
class ABC
{
  public static $value = 10;
}
ABC::$value++;
echo ABC::$value;
}
?>


by BrainBellupdated
Advertisement: