Static Methods & Properties in PHP Class

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 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. However, they can use other static members.

Referencing Static Members

Unlike instance members, static members are not accessed using the single arrow operator (->). To call a static function or method, 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
}

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

So, static members can be accessed outside of the class using the class name and the :: scope operator. Also, to access the static members inside the class, you can use the self keyword followed by the :: scope operator.

To access static properties or methods from subclasses, we use the parent keyword followed by the :: scope operator.  

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.

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive