I have piece of code:
class example {
public function say($x) {
if ($x > 0) {
echo $x;
$this->say($x - 1);
}
else echo "0<br>\n";
}
}
example::say(5);
Calling it I have:
5
Fatal error: Using $this when not in object context in (...).php on line 5
Why is this happening? What is happening to function ‘say’? I see it’s called once from outside a class, but why inside class PHP claims ‘say’ isn’t accesible by ‘$this->’?
The error message is actually pretty clear: You cannot use $this, as you never created an instance of your example class. If you want to call your method statically, use this:
Or in a more object oriented way:
You can call a non-static method statically, but you shouldn’t (and this will only work if the method does not use $this). This is why PHP warns you if E_STRICT is enabled