How to get class of $this in Magento

Being a frontend developer in Magento you have to have more familiarity and experience with PHP than in systems that have a strict templating language which more truly divides frontend from backend developers. When working in the template files you’ll often see calls to the $this object. Without a firm grasp of the Magento object structure (and a little luck) it can be confusing to know which object $this is referring to.

What you need to do is find the class that is responsible for this object and luckily PHP has a built in function that can help you do just that. All you need to do is go into your .phtml files and directly below the call to the $this object you are interested in knowing more about you put this code:

<?php
    echo 'The class of this object is ';
    echo get_class($this);
?>

Now refresh the frontend webpage that you are editing and you will see the output, ‘The class of this object is [class name]‘. For example when working with catalog objects you may see, ‘The class of this object is Mage_Catalog_Block_Product_View’. You can now go directly to the file that creates that object.

How do I know which file it is?

You have two methods, manual and search. You can search for the object class using your IDE or grep for cli users. This will return all instances of the class name to include where it has been extended. But if you are looking for the original class itself simply prepend the word ‘Class’ to the object in your search (i.e. ‘Class Mage_Catalog_Block_Product_View’). This will show you where the original class is defined.

The other method is simply following the class name as it tells you the file path. Since we’re dealing with php objects we know its going to be in the /app directory. Assuming it is a standard Magento class and not from a 3rd party extension we know it will be /app/code/core. Using /app/code/core as our starting point the rest is easy Mage_Catalog_Block_Product_View becomes app/code/core/Mage/Catalog/Block/Product/View.php.

That’s it!

Hope this helps you in your development as always feel free to ask questions.