Magento 2: How to use helper in PHTML?

Magento 2 - How to use helper in PHTML

Magento 2, an open-source e-commerce platform, offers a variety of tools for developers to create robust online stores. One such tool is the Helper class, a collection of methods that can be used globally.

PHTML is a file extension for PHP files in Magento 2, and it’s where the HTML and PHP logic for a view is stored.

Creating a Helper in Magento 2

Helpers in Magento 2 are classes that contain methods which can be accessed from any location in your code. They are typically used for functions that are widely used throughout your codebase.

Here’s an example of how to create a helper:

In this code:

  • We define a namespace (Vendor\Module\Helper) to avoid naming conflicts.
  • We extend the AbstractHelper class provided by Magento 2.
  • We define a method customHelperFunction that takes two arguments ($arg1, $arg2). This is where you’ll put the logic for your helper function.

Remember to replace Vendor\Module it with your actual vendor and module name.

Using the Helper in a PHTML File

Once you’ve created your helper, you can use it in a PHTML file like this:

In this code:

  • We use the $this->helper() method to get an instance of our helper class. The argument for this method is the fully qualified name of our helper class.
  • We then call the customHelperFunction method on our helper instance, passing in the arguments 'arg1' and 'arg2'.


Helpers in Magento 2 are a powerful tool for developers, allowing you to write reusable code that can be accessed from anywhere in your application. By creating a helper and using it in a PHTML file, you can make your Magento 2 development more efficient and maintainable.

I hope this tutorial finds you helpful, See you in the next blog.

You may also like :

How to Remove Sample Data from Magento 2

Create CMS Block Programmatically Magento 2

Patch to Debug Blocks and Containers in Magento 2

Leave a Reply

Your email address will not be published. Required fields are marked *