Search code examples
phpstaticthisself

Oddity of static:: calling a method that contains $this


In this example I get the fatal error "Fatal error: Using $this when not in object context" as expected

class ctis_parent{
    public function objFunc(){
        var_dump('Called succes');
    }

    public static function call(){

        $this->objFunc(); 
    }

    public function __construct(){
        self::call();
    }

}

new ctis_parent();

But if remove static keyword from definition of call() method all work fine, why?

class ctis_parent{
    public function objFunc(){
        var_dump('Called succes');
    }

    public  function call(){
        $this->objFunc();
    }

    public function __construct(){
        self::call();
    }

}

new ctis_parent(); 

//string 'Called succes' (length=13)

Solution

  • Because you're using $this when you're not in an object. Well, you're not REALLY, but with the static declaration, people could do:

    ctis_parent::call();
    

    Where, $this would be illegal.

    See the docs for static.