News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

PHP Tutorial – 13 – Static and Constants

The static keyword can be used to declare properties and methods that can be accessed without having to create an instance of the class. Static (class) members only exist in one copy, which belongs to the class itself, whereas instance (non-static) members are created as new copies for each new object.

class MyCircle
{
  // Instance members (one per object)
  public $r = 10;
  function getArea() {}
 
  // Static/class members (only one copy)
  static $pi = 3.14; 
  static function newArea($a) {} 
}

Static methods cannot use instance members since these methods are not part of an instance. They can however use other static members.

Referencing static members

Unlike instance members, static members are not accessed using the single arrow operator (->). Instead, in order to reference static members inside a class the member must be prefixed with the self keyword followed by the scope resolution operator (::). The self keyword is an alias for the class name, so alternatively the actual name of the class can be used.

static function newArea($a) 
{
  return self::$pi * $a * $a;     // ok
  return MyCircle::$pi * $a * $a; // alternative
}

This same syntax is used to access static members from an instance method. Note that in contrast to static methods, instance methods can use both static and instance members.

function getArea()
{ 
  return self::newArea($this->$r); 
}

To access static members from outside the class the name of the class needs to be used followed by the scope resolution operator (::).

class MyCircle
{ 
  static $pi = 3.14; 
 
  static function newArea($a) 
  {
    return self::$pi * $a * $a;
  }
}
 
echo MyCircle::$pi; // "3.14"
echo MyCircle::newArea(10); // "314"

The advantage of static members can be seen here in that they can be used without having to create an instance of the class. Methods should therefore be declared static if they perform a generic function independently of instance variables. Likewise, properties should be declared static if there is only need for a single instance of the variable.

Static variables

Local variables can be declared static to make the function remember its value. Such a static variable only exists in the local function’s scope, but it does not lose its value when the function ends. This can for example be used to count the number of times a function is called.

function add()
{
  static $val = 0;
  echo $val++;
}
 
add(); // "0"
add(); // "1"
add(); // "2"

The initial value that a static variable is given will only be set once. Keep in mind that static properties and static variables may only be initialized with a constant and not with an expression, such as another variable or a function return value.

Late static bindings

As mentioned before, the self keyword is an alias for the class name of the enclosing class. This means that the keyword will refer to its enclosing class even when it is called from the context of a child class.

class MyParent
{
  protected static $val = 'parent';
 
  public static function getVal() 
  {
    return self::$val;
  }
}
 
class MyChild extends MyParent
{
  protected static $val = 'child';
}
 
echo MyChild::getVal(); // "parent"

To get the class reference to evaluate to the actual calling class, the static keyword needs to be used instead of the self keyword. This feature is called late static bindings and was added in PHP 5.3.

class MyParent
{
  protected static $val = 'parent';
 
  public static function getLateBindingVal()
  {
    return static::$val;
  }
}
 
class MyChild extends MyParent
{
  protected static $val = 'child';
}
 
echo MyChild::getLateBindingVal(); // "child"

Constants

A constant is a variable with a value that cannot be changed in the script. Such a value must therefore be assigned at the same time as the constant is created. PHP provides two methods for creating constants: the const modifier and the define function.

Const

The const modifier is used to create class constants. Unlike regular properties, class constants do not have an access level specified, as they are always publicly visible. They also do not use the dollar sign parser token ($). The naming convention for constants is all-uppercase, with underscores separating each word.

class MyCircle
{
  const PI = 3.14;
}

Constants must be assigned a value when they are created. Like static properties, a constant may only be initialized with a constant value and not with an expression. Class constants are referenced in the same way as static properties, except that they do not use the dollar sign.

echo MyCircle::PI; // "3.14"

The const modifier may not be applied to local variables or parameters. However, as of PHP 5.3 const can be used to create global constants. Such a constant is defined in the global scope and can be accessed anywhere in the script.

const PI = 3.14;
echo PI; // "3.14"

Define

The define function can create both global and local constants, but not class constants. The first argument to this function is the constant’s name and the second is its value.

define('DEBUG', 1);

Just as constants created with const, define constants are used without the dollar sign and their value cannot be modified.

echo DEBUG; // "1"

Like constants created with const, the value for define may be any scalar data type: integer, float, string or bool. However, unlike const the define function allows an expression to be used in the assignment, such as a variable or the result of a mathematical expression.

define('ONE', 1);     // 1
define('TWO', ONE+1); // 2

Constant are case-sensitive by default. However, the define function takes a third optional argument which may be set to true to create a case-insensitive constant.

define('DEBUG', 1, true);
echo debug; // "1"

To check whether a constant already exists the defined function can be used. This function works both for constants created with const and define.

if (!defined('PI')) 
  define('PI', 3.14);

Const and define

The const modifier creates a compile-time constant and so the compiler will replace all usage of the constant with its value. In contrast, define creates a run-time constant which is not set until run-time. This is the reason why define constants may be assigned with expressional values, whereas const requires constant values which are known at compile-time.

const PI = 3.14;         // compile-time constant
define('BIT_2', 1 << 2); // run-time constant

Only const may be used for class constants and only define for local constants. However, when creating global constants both const and define are allowed. In these circumstances using const is generally preferable. Because const is a language construct it reads better than define which is a function. Compile-time constants are also slightly faster than run-time constants. The only exception is when the constant is conditionally defined, or an expressional value is required, in which case define must be used.

Constant guideline

In general, it is a good idea to create constants instead of variables if their values do not need to be changed. This ensures that the variables will not be changed anywhere in the script by mistake, which in turn helps to prevent bugs.

Magic constants

PHP provides eight predefined constants. These are called magic constants as their values change depending on where they are used.

NameDescription
__LINE__Current line number of the file.
__FILE__Full path and filename of the file.
__DIR__Directory of the file.
__FUNCTION__Function name.
__CLASS__Class name including namespace.
__TRAIT__Trait name including namespace.
__METHOD__Class method name.
__NAMESPACE__Current namespace.

Magic constants are especially useful for debugging purposes. For example, the value of __LINE__ depends on the line on which it appears in the script.

if(!isset($var))
{
  echo '$var not set on line ' . __LINE__;
}
Recommended additional reading:
Sams - Teach Yourself PHP in 24 Hours