1

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)

2 Answers 2

1

A static function, by definition doesn't need the class being instantiated, so it doesn't have access to the $this-> reference, which points to the current instance. If an instance doesn't exist, it can't be pointed to. Makes sense.

0

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.

5
  • I know that I use static in the wrong context but why in the second example it works? Commented Sep 6, 2012 at 20:52
  • @yurisnk: Why shouldn't it work? After the constructor is magically called, $this exists, and you're calling it's function objFunc();
    – Josh
    Commented Sep 6, 2012 at 20:53
  • @yurisnk: when you're calling from the constructor, you're calling from a method that can only be invoked when a new instance is being created, so there is a $this, and calling a method (that you didn't declare static) statically from within the instance is just fine Commented Sep 6, 2012 at 20:54
  • @elias-van-ootegem it means that when we call the non static method with the static:: keyword this is equivalent to calling with $this-> ? Commented Sep 6, 2012 at 21:03
  • 1
    Yes, sort of but :: is what is called a scope resolution operator, so self::call() just means call function call in the scope of self::. On the whole, it's better left for use of statics, to avoid confusion. I was rather surprized to see that self::nonstaticMethod() worked. I thought it didn't anymore... Commented Sep 6, 2012 at 21:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.