skip to Main Content

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


  1. 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.

    Declaring class properties or methods as static makes them accessible
    without needing an instantiation of the class. These can also be
    accessed statically within an instantiated class object.

    … Because
    static methods are callable without an instance of the object created,
    the pseudo-variable $this is not available inside methods declared as
    static.

    Login or Signup to reply.
  2. From the docs: PHP Static Keyword:

    Static properties are accessed using the Scope Resolution Operator (::) and cannot be accessed through the object operator (->).

    And here is the important part:

    It’s possible to reference the class using a variable. The variable’s value cannot be a keyword (e.g. self, parent and static).

    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:

    echo $test::$test;   // This works in addition to: echo Test::$test;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search