Paul Ruiz
Paul Ruiz

Reputation: 23

Why does calling this method statically work?

class Duck {
  public function quack() {
    $this­->swim();
  }
  public function swim() {
    echo 'I\'m swimming!';
  }
}
class Plane {
  public function fly() {
    Duck::quack(); 
  }
  public function swim()
  {
  echo 'I can\'t swim! People are DROWNING!';
  } 
}
$plane = new Plane(); 
$plane-­>fly(); 

I got asked the above question and gave the answer that the output is an error illegally calling static method.
But it actually prints "I'm swimming!".
Could somebody please explain why this happens?

Upvotes: 2

Views: 74

Answers (2)

Craig Taub
Craig Taub

Reputation: 4179

Something to note with PHP 5.3 (and public methods):

CAN call public methods statically from anywhere INSIDE Object context (only if inside instantiated object)...even if not declared static

Duck::quack();

CANT call protected method in same scenario.

Duck::quack(); //error
protected function quack() { }

CANT call public properties (instance variables) statically from anywhere INSIDE Object context, unless declared static...

class Duck {
 public $hello = 'hello there';   
}
class Plane {
 Duck::$hello; //error
}

CANT call public methods (or properties) statically from OUTSIDE object context..unless declared static

Duck::quack(); //error

Other languages use this type of engine flexibility, calling any public method statically as long as from inside Object context.
As mentioned (by @poitroae) it works like this by default, but if you turn on E_STRICT you'll get an error.

ALSO:
It is a known idiosyncrasy with PHP that you should'nt be allowed to call $this in this Context. The program should be under Class Context at this point (being called statically) but $this works which is akin to Object Context.
If this were a statically declared Method than calling $this would cause an instant fatal error.

Hope that helps

Upvotes: 0

poitroae
poitroae

Reputation: 21367

It works by default, but if you turn on E_STRICT you'll get

PHP Strict Standards: Non-static method Duck::quack() should not be called statically in...

PHP sees that you wanted swim() to be actually static and so it let's you simply call it.

Upvotes: 2

Related Questions