How to access constant defined in child class from parent class functions?

I saw this example from php.net:

<?php
class MyClass {

     const MY_CONST = "yonder";

     public function __construct() {

          $c = get_class( $this );
          echo $c::MY_CONST;
     }
}

class ChildClass extends MyClass {

     const MY_CONST = "bar";
}

$x = new ChildClass(); // prints 'bar'
$y = new MyClass(); // prints 'yonder'
?>

But $c::MY_CONST is only recognized in version 5.3.0 or later. The class I'm writing may be distributed a lot.

Basically, I have defined a constant in ChildClass and one of the functions in MyClass (father class) needs to use the constant. Any idea?


Solution 1:

How about using static::MY_CONST?

Solution 2:

Since php 5.3:

Use static::MY_CONST


More details on static

In this case the keyword static is a reference to the actually called class.

This illustrates the difference between static $var, static::$var and self::$var:

class Base {
    const VALUE = 'base';

    static function testSelf() {
        // Output is always 'base', because `self::` is always class Base
        return self::VALUE;
    }

    static function testStatic() {
        // Output is variable: `static::` is a reference to the called class.
        return static::VALUE;
    }
}

class Child extends Base {
    const VALUE = 'child';
}

echo Base::testStatic();  // output: base
echo Base::testSelf();    // output: base

echo Child::testStatic(); // output: child
echo Child::testSelf();   // output: base

Also note that the keyword static has 2 quite different meanings:

class StaticDemo {
    static function demo() {
        // Type 1: `static` defines a static variable.
        static $Var = 'bar';

        // Type 2: `static::` is a reference to the called class.
        return static::VALUE;
    }
}

Solution 3:

Instead of

$c = get_class( $this );
echo $c::MY_CONST;

Do this

$c = get_class( $this );
echo constant($c . '::MY_CONST');