$this — Anyone who’s opened a Magento template phtml file has seen the $this object and wondered which this is that? Turns out it’s pretty simple to track down.
In a template file, $this is a object variable that contains a block class. It’s typically a different object in every template page. That’s why, when you’re first messing around with Magento templates, you can get tripped up by $this having different functionality in every block.
The $this object variable contains specific block that is being displayed, or rendered, in the phtml file. Knowing what properties, collections and functions are available in that block is an important step in easily developing and updating templates.
Sometimes finding the right model and class is as easy as looking at the folder path where the phtml file located. For example, the $this in phtml file –
Is defined by the class in –
You can verify this by looking in the template files to find the template file and the block type that is defined for it.
<block type="catalog/product_list" name="product_list" template="catalog/product/list.phtml">
Of course there is the chance that the block is not defined in the layout file. Since Magento allows for (many) other mechanisms to define layout blocks, searching the layout files won’t help. In this case, you can just have PHP tell you what class $this is adding the following code to the template file –
<?php echo ‘this is ‘.get_class($this) ?>
Which will show up on the front end looking like –
And for added bonus, if you want to know what class $this is child of you can always use –
<?php echo ‘this is a child of ‘.get_parent_class($this) ?>
I hope this has helped you learn a bit about Magento and will make $this a little less mysterious.