Can we use $this
outside of class. Please look at the example below,
<?php
class Animal {
public function whichClass() {
echo "I am an Animal!";
}
public function sayClassName() {
$this->whichClass();
}
}
class Tiger extends Animal {
public function whichClass() {
echo "I am a Tiger!";
}
public function anotherClass() {
echo "I am a another Tiger!";
}
}
$tigerObj = new Tiger();
//Tiger::whichClass();
$this->anotherClass();
Here I have created new object $tigerObj = new Tiger();
after that I tried to use $this
but it throwing error. So is that possible to use $this
from outside of the class ? If no,
$this
refers to the current object. So why don't we use this ?
NO you can't use $this outside the scope of a class
example :
generates the following error :
Fatal error: Cannot re-assign $this on line 2
Its not possible to use $this in this way, you can create object of that class and then extend the methods which you would like to call. See below ...
You will get result "I am a another Tiger!"
$this is impossible to use outside class so you can make static method, and use like this Tiger::anotherClass. Link to doc