(734)545-8017

The Human Element Blog

Magento Template Development – Finding $This

Posted Feb 11, 2015 by

findingThis

And you thought Nemo had it hard.

$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 –

/app/design/frontend/enterprise/default/template/catalog/product/list.phtml

Is defined by the class in –
/app/code/core/Mage/Catalog/Block/Product/List.php

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">
</block>

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 –
this is Mage_Catalog_Block_Product_View

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) ?>

this is a child of Mage_Catalog_Block_Product_Abstract

I hope this has helped you learn a bit about Magento and will make $this a little less mysterious.

Posted By

Chief Technology Officer

Comments (0)

Post a comment