Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting class constant inside class

Tags:

php

What's the difference between self::CONSTANT_NAME and static::CONSTANT_NAME?

Is calling constant via static:: only 5.3 feature?

like image 477
Kirzilla Avatar asked Dec 24 '10 10:12

Kirzilla


People also ask

How do you define a constant inside a class?

A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.

Where do you put constants in a class?

Constants that are specific to a class should go in that class's interface.

How can I get constant outside class in PHP?

Class constants are useful when you need to declare some constant data (which does not change) within a class. There are two ways to access class constant: Outside the Class: The class constant is accessed by using the class name followed by the scope resolution operator (::) followed by the constant name.


2 Answers

When you use static::NAME it's a feature called late static binding (or LSB). More information about this feature is at the php.net documentation page of LSB: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

An example is this use case:

<?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 outputs A, which is not always desirable. Now replacing self with static creates this:

<?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 might expect, it ouputs "B"

like image 149
Jurian Sluiman Avatar answered Oct 19 '22 19:10

Jurian Sluiman


The difference is pretty much what late static bindings are all about.

Short explanation:

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

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

This means that there's only a difference if we are talking about classes in the same inheritance hierarchy.

like image 5
Jon Avatar answered Oct 19 '22 20:10

Jon