In PHP 5, what is the difference between using const and static?
When is each appropriate? And what role does public, pr
When talking about class inheritance you can differentiate between the constant or variable in different scopes by using self and static key words. Check this example which illustrates how to access what:
class Person
{
static $type = 'person';
const TYPE = 'person';
static public function getType(){
var_dump(self::TYPE);
var_dump(static::TYPE);
var_dump(self::$type);
var_dump(static::$type);
}
}
class Pirate extends Person
{
static $type = 'pirate';
const TYPE = 'pirate';
}
And then do:
$pirate = new Pirate();
$pirate::getType();
or:
Pirate::getType();
Output:
string(6) "person"
string(6) "pirate"
string(6) "person"
string(6) "pirate"
In other words self:: refers to the static property and constant from the same scope where it is being called (in this case the Person superclass), while static:: will access the property and constant from the scope in run time (so in this case in the Pirate subclass).
Read more on late static binding here on php.net.
Also check the answer on another question here and here.