There was an interesting question in a practice test that I did not understand the answer to. What is the output of the following code:
<?php class Foo { public $name = 'Andrew'; public function getName() { echo $this->name; } } class Bar extends Foo { public $name = 'John'; public function getName() { Foo::getName(); } } $a = new Bar; $a->getName(); ?>
Initially, I thought this was produce an error because static methods can not reference $this (atleast in PHP5). I tested this myself and it actually outputs John.
I added Foo::getName(); at the end of the script and did get the error I was expecting. So, what changes when you call a static method from within a class that extends the class you’re calling from?
Would anyone mind explaining in detail exactly what is going on here?
$this to the object in whose context the method was called. So: $this is $a->getName() is $a. $this in $fooInstance->getName() would be $fooInstance. In the case that $this is set (in an object $a’s method call) and we call a static method, $this remains assigned to $a.
Seems like quite a lot of confusion could come out of using this feature. 🙂