Static Method Inheritance

We know static methods are callable without instantiating objects. But if it is used from explicit class name, php violates inheritance rule by referencing the current class instead of the called class. Moreover if we use ‘self’ to call the method , it will represent the current class.

Lets see the following code

class BaseClass
{
static function dump()
{
echo __CLASS__ . '::dump()';
}
static function callDump()
{
self::dump(); // self represents the current class
}
}


class ChildClass extends BaseClass
{
static function dump()
{
echo __CLASS__. '::dump()';
}
}
ChildClass::callDump();

In the above code , what the inheritance rule says , it says that the output is supposed to ChildClass::dump() but real output is BaseClass::dump(). This is because ‘self’ always represents the current class.

To solve this limitation PHP introduce Late Static Binding (LSB) from PHP version 5.3.0 that can be used to reference the current class. It is represented as ‘static::’. So the above code will be as following


class BaseClass
{
static function dump()
{
echo __CLASS__ . '::dump()';
}


static function callDump()
{
static::dump(); // static refers the called class
}
}

class ChildClass extends BaseClass
{
static function dump()
{
echo __CLASS__. '::dump()';
}
}

ChildClass::callDump();

Now the above code will output ChildClass::dump(), but ‘static::’ is available from PHP version 5.3.0

For more info please visit the following links
Static Keyworkd
Late Static Binding

Thank$
$haymoL
eXpLoRinG PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: