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?
I couldn't get it to work with const as it prints "yonderyonder" (that's the thing about constants, they don't change), but it works fine with var:
How about using
static::MY_CONST
?If you need to access constants, properties, methods of classes or objects you can use reflection, it provides much more details about structure of the object.
example:
Instead of
Do this
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
andself::$var
:Also note that the keyword
static
has 2 quite different meanings: