Getting a class constant inside a class

What is the difference between self::CONSTANT_NAME and static::CONSTANT_NAME ?

Is calling a constant via static:: just a 5.3 function?

+7
source share
2 answers

The difference is largely that of late static bindings .

Brief explanation:

self:: will refer to the type of the class inside which the code is written using self ::.

static:: will refer to the class type of the actual object on which the code is executed using static ::.

This means that there is only a difference if we talk about classes in the same inheritance hierarchy.

+5
source

When you use static :: NAME, this is a function called late static binding (or LSB). For more information about this function, see the php.net LSB documentation page: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

An example is the following example:

 <?php class A { public static function who() { echo __CLASS__; } public static function test() { self::who(); } } class B extends A { public static function who() { echo __CLASS__; } } B::test(); ?> 

This infers A, which is not always desirable. Now replacing self with static creates the following:

 <?php class A { public static function who() { echo __CLASS__; } public static function test() { static::who(); // Here comes Late Static Bindings } } class B extends A { public static function who() { echo __CLASS__; } } B::test(); ?> 

And, as you would expect, it displays "B"

+6
source

All Articles