I know there is a difference between static::
and self::
like in this example ( from https://mcmap.net/q/173977/-overriding-class-constants-vs-properties )
<?php
class One
{
const TEST = "test1";
function test() { echo static::TEST; }
}
class Two extends One
{
const TEST = "test2";
}
$c = new Two();
$c->test();
Which returns test2 when static::TEST
is used and test1 when self::TEST
is used.
But it also returns test2 when $this::TEST
is used.
static::TEST
can be used inside a static method, whereas $this::TEST
requires an instance before being used (so non-usable in static methods).
But if one cannot use $this::
in static methods, static::
can be used in non-static methods (like in the example).
So, what is the difference between static:: and $this:: in a non static method?
Optional complete test
<?php
abstract class AOne
{
const TEST = "test1";
abstract public function test();
}
class OneStatic extends AOne
{
public function test()
{
return static::TEST;
}
}
class TwoStatic extends OneStatic
{
const TEST = "test2";
}
class OneSelf extends AOne
{
public function test()
{
return self::TEST;
}
}
class TwoSelf extends OneSelf
{
const TEST = "test2";
}
class OneThis extends AOne
{
public function test()
{
return $this::TEST;
}
}
class TwoThis extends OneThis
{
const TEST = "test2";
}
$objects = array(
'one, static::' => new OneStatic(),
'two, static::' => new TwoStatic(),
'one, self::' => new OneSelf(),
'two, self::' => new TwoSelf(),
'one, $this::' => new OneThis(),
'two, $this::' => new TwoThis(),
);
$results = array();
foreach ($objects as $name=>$object)
$results[$name] = $object->test();
var_dump($results);
?>
Which yields
- 'one, static::' => 'test1'
- 'two, static::' => 'test2'
- 'one, self::' => 'test1'
- 'two, self::' => 'test1'
- 'one, $this::' => 'test1'
- 'two, $this::' => 'test2'
So self refers to the class where the method is defined, but there's no difference between $this::
and static::
in these non static methods.