In all the examples in this appendix, we are using instances (objects) of classes, which modeled real-life entities. However, in PHP5 it is possible to use static properties and methods. Static properties are variables that are common to all the instances of the given class so that, if a static property is changed, it will get changed for all objects belonging to the class.
A static property is declared just like a regular one, but with a special static keyword:
class DataModel
{
public static $conn = null;
}
The static properties can be accessed without even creating an instance of the class:
if(!DataModel::$conn) { echo 'Connection not established!'; }
The syntax for accessing a static property is as follows: the class name, then double semicolon, and then the property's name. Note that with static properties (unlike with regular properties), the dollar sign, $
, sign must be present.
Static methods, just like static properties, can be accessed without instantiating an object. They are declared and accessed in the following way:
class DataModel { public static $conn = null; static function getConn() { if(!DataModel::$conn) { DataModel::$conn = new PDO('sqlite:./my.db', 'user', 'pass'); } return DataModel::$conn; } } $conn = DataModel::getConn();
The declaration of a static method has the static
keyword followed by a regular method declaration. The method is accessed by the class name followed by a double semicolon and then the method name.
The static properties and methods can be accessed inside the class declaration using the shortcut keyword self:
class DataModel { public static $conn = null; static function getConn() { if(!self::$conn) { self::$conn = new PDO('sqlite:./my.db', 'user', 'pass'); } return self::$conn; } } $conn = DataModel::getConn();
There is also a major difference with the definition of static methods. You cannot use the $this
variable (as there is no object to which the $this
variable can refer).
Another 'static' feature of classes is class constants. A class constant acts like a static property, but its value cannot be changed. Class constants always must have their values assigned in the class declaration section, and they don't have the dollar sign before them (so they are named just like regular PHP constants). Class constants are mostly used for keeping the global namespace cleaner (which is also one of the uses for static methods):
class DataModel
{
public static $conn = null;
const ORDER_AZ = 1;
const ORDER_ZA = 2;
static function getConn()
{
if(!self::$conn) {
self::$conn = new PDO('sqlite:./my.db', 'user', 'pass');
}
return self::$conn;
}
static function getItems($sortMode)
{
if($sortMode == self::ORDER_AZ) {
$sql = // SQL for ascending
}
else {
$sql = // SQL for descending
}
}
}
$items = DataModel::getItems(DataModel::ORDER_ZA);
An attempt to assign a value to a class constant in the code will lead to a parse error.