Why can not I use $ this inside a static class?

6

In the example below, I wanted to know why I can not use $this inside a static class ?

<?php

class A{
     public static function hello(){
        echo 'hello';
    }
}

class B extends A{  
    public function ok(){
        echo 'ok';
    }

    public static function fprint(){
        A::hello();
        $this->ok();
    }   
}

$obj = new B;
$obj->fprint();
?>

The problem is in the fprint method. I understand that a static method can be used without the need of an object, but if I call an object, as I did, the fprint method does not need to use it to call the hello method, since I use class A to this, and $this will serve to call the ok method with the instance object that I created. I do not understand why this gives error.

The error returned:

  

Fatal error: Using $ this when not in object context

    
asked by anonymous 16.12.2015 / 04:24

2 answers

8

$this represents the instance of a class. You should not use it for static methods simply because there is no instance concept in them. In fact, the reason for using a static method is the independence of an instantiated object.
(also mentioned by @utluiz almost the same time I posted it.)

The question is another: if you need the instance, why declare the method with static ?

Note that this is how it works normally. I even passed the static to the above method to see the :: scope resolution syntax you used in B::ok() in action (see note at the end):

<?php

class A{
     public static function hello(){
        echo 'hello';
    }
}

class B extends A{  
    public static function ok(){
        echo 'ok';
    }

    public function fprint(){
        A::hello();
        $this->ok();
    }   
}

$obj = new B;
$obj->fprint();
?>

See working at IDEONE .

Another example:

<?php

class A{
     public static function hello(){
        echo 'hello';
    }
}

class B extends A{  
    public function ok(){
        echo 'ok';
    }

    public static function fprint(){
        A::hello();
        B::ok();
    }   
}

$obj = new B;
$obj->fprint();
?>

See this version on IDEONE .

This is also working in IDEONE, since we are no longer using the instance ( $this ), but rather making a new call, this time static, to the ok() method.

Important Note: In the second example the static call will only work without the method being static if E_STRICT is not active. This is an operation that may be allowed for compatibility with older versions of PHP, the reverse not. In a normal situation, you would have both static methods.

Some manual references:
Paamayim Nekudotayim
Static

16.12.2015 / 04:48
3

Basically, you can not use $this directly in static methods because they are not directly bound to objects or instances of the class, whereas non-static methods always refer to objects or instances of that class. In response to this, you can define your method / prority as static so you can use it in static methods.

    
16.12.2015 / 04:52