How to find out what $this is?

by shenkwen   Last Updated May 16, 2018 10:10 AM

I am not unfamiliar with this parameter in JavaScript. But in Joomla's PHP files, I often come across $this that seems coming from nowhere(Not in an object). To clarify some basic notions, here are some questions:

  1. In JavaScript, generally, if this is not inside an object, then it is referring to the global object, which in a browser environment is window. I understand that in PHP there is no such thing, but when it comes to what $this is referring to, is there any similar thing?

  2. I think in most cases, for those $this not in an object, they actually reside in an object that is defined in another file, which 'require's current file, am I right? If yes, how can I find out where that file is, or what object $this resides in? Using the extension "J!dump" I can actually see what $this is, but I still want to know how to find out the parent object.

Tags : php


Answers 1


To answer 1, no there is no global PHP $this variable that correlates with JavaScripts this varaible. This can be easily tested with a simple PHP file:

echo $this;

which will give you an error.

To answer 2, $this is always inside a class. What I think you are trying to understand is class inheritance. So say you are looking at the file cat.php:

class Cat extends Animal {

   protected $meow = 'meeoooowww';

   public function Meow() {
     echo $this->meow . ' I am ' . $this->age . ' years old';
   }

}

and somewhere else you have a file animal.php:

class Animal {

   protected $age = '10';

   public function run() {
     echo "I'm running";
  }
}

Finally you create a new cat in some other file:

$tinkles = new Cat();
$tinkles->run();
echo "<br>";
$tinkles->meow();

You are going to see this outputted:

I'm running
meeoooowww I am 10 years old

Note how the cat has inherited the function (run) and propertie (age) from Animal by using "extends Animal" as part of the class declaration.

PHP then has several methods for understanding what the class is, In the next snippet we will add an introspect() function, using those methods:

class Cat extends Animal {

   protected $meow = 'meeoooowww';

   public function Meow() {
     echo $this->meow;
   }

   public function introspect() {
     echo "My class is ". get_class($this) . "<br>";
     echo "My ancestor class is " . get_parent_class($this);
   }

}

So now:

$tinkles = new Cat();
$tinkles->introspect();

will produce:

My class is Cat
My ancestor class is Animal

Finding out where those files resides can require some detective skills if you are not familiar with the framework.

You would benefit from setting up xdebug for example to be able to step through what happens when your code is executed.

Also a good IDE such as PHPStorm will allow you to click on the class name, for example "Animal" in "class Cat extends Animal" to open up that file directly.

Rob Clayburn
Rob Clayburn
October 13, 2015 19:58 PM

Related Questions