I learned that we can’t use $this::
to call static class property and should use self::
or static::
so any idea why this code works ?
<?php
class Test {
public static string $test = 'test';
public function __construct()
{
}
public function test(): void
{
echo $this::$test;
}
}
$test = new Test();
$test->test();
2
Answers
You can access static property or call static method with
$this
, but you can not refer$this
inside/within a static method as its not an instance context.From the docs: PHP Static Keyword:
And here is the important part:
So you can access static properties, static methods, and static constants with $this – which is a variable – within a class definition’s code.
And in your code above you could also access the $test property from the outside of the class via the instance $test: