Static Properties in PHP

By: Andi, Stig and Derick  

Classes can declare properties. Each instance of the class (i.e., object) has its own copy of these properties. However, a class can also contain static properties. Unlike regular properties, these belong to the class itself and not to any instance of it. Therefore, they are often called class properties as opposed to object or instance properties. You can also think of static properties as global variables that sit inside a class but are accessible from anywhere via the class.

Static properties are defined by using the static keyword:

class MyClass {

static $myStaticVariable;

static $myInitializedStaticVariable = 0;

}

To access static properties, you have to qualify the property name with the class it sits in

MyClass::$myInitializedStaticVariable++;

print MyClass::$myInitializedStaticVariable;

This example prints the number 1.

If you’re accessing the member from inside one of the class methods, you may also refer to the property by prefixing it with the special class name self, which is short for the class to which the method belongs:

class MyClass {

static $myInitializedStaticVariable = 0;

function myMethod()

{

print self::$myInitializedStaticVariable;

}

}

$obj = new MyClass();

$obj->myMethod();

This example prints the number 0.

You are probably asking yourself if this whole static business is really useful. One example of using it is to assign a unique id to all instances of a class:

class MyUniqueIdClass {

static $idCounter = 0;

public $uniqueId;

function __construct()

{

self::$idCounter++;

$this->uniqueId = self::$idCounter;

}

}

$obj1 = new MyUniqueIdClass();

print $obj1->uniqueId . "\n";

$obj2 = new MyUniqueIdClass();

print $obj2->uniqueId . "\n";

This prints

1

2

The first object’s $uniqueId property variable equals 1 and the latter object equals 2.




Archived Comments


Most Viewed Articles (in PHP )

Reading word by word from a file in PHP

Get the next working day in PHP

Installing PHP with nginx-server under windows

PHP ./configure RESULTING IN [email protected]_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Function to force strict boolean values in PHP

Function to convert strings to strict booleans in PHP

Function to sort array by elements and count of element in PHP

Malware: global $ob_starting;

Function to return number of digits of an integer in PHP

Latest Articles (in PHP)

Comment on this tutorial