Calling non-static method with double-colon(::)

PHP is very loose with static vs. non-static methods. One thing I don’t see noted here is that if you call a non-static method, ns statically from within a non-static method of class C, $this inside ns will refer to your instance of C.

class A 
{
    public function test()
    {
        echo $this->name;
    }
}

class C 
{
     public function q()
     {
         $this->name="hello";
         A::test();
     }
}

$c = new C;
$c->q();// prints hello

This is actually an error of some kind if you have strict error reporting on, but not otherwise.

Leave a Comment