In a normal class, all the properties and methods are linked to a specific instance. So, two different instances could have two different values for the same property. PHP allows you to have properties and methods linked to the class itself rather than to the object. These properties and methods are defined with the keyword static.

Static methods in a class can be called without an instance of the object created. Pseudo variable $this is not available inside the method declared as static.

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 use other static members, however.

Referencing Static Members

Unlike instance members, static members are not accessed using the single arrow operator (->). To call a static function or method, you can simply type the class name, scope resolution operator (double colons, ::), and the method name. to reference static members inside a class, the member must be prefixed with the self keyword followed by the scope resolution operator (::).

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

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 is that they can be used without having to create an instance of the class. Therefore, methods should 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 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"

 

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive