Magento 2 call block function in phtml

Magento 2 call any block function in phtml

This tutorial is about magento 2 call block function in phtml. First of all i assume that you are familiar with magento 2 and hence you are at this level where you want to know how in magento 2 call any block function in phtml. Above all if you are not familiar and are looking for basics please look for magento 2 basic tutorials.

Seems like i have conveyed my message so lets start our tutorial and focus on our topic. For example if you want to call your custom block function in product list.phtml?.How can we do it? I will try to explain it in a simple way.

Call custom block funtion

Lets have a look at the code.
For example your block class is as below

namespace QaisarSatti\HelloWorld\Block;
use Magento\Framework\View\Element\Template;

class Test extends Template
    public function getMyCustomMethod()
        return 'Get Your custom method';

Then in any phtml file,you can use the following code to get method of this block.

$blockObj= $block->getLayout()->createBlock('QaisarSatti\HelloWorld\Block\Test');
echo $blockObj->getMyCustomMethod();

That is how it can be done.Certainly, i have tried to explain these codes and their logic in a simple way, i hope they help you learn in an easy and better way. That’s it from this tutorial.

Since these tutorials are for learning purpose please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.


Recent Blogs





Leave a Reply