magento block function call

Here We will know, How to call any block function in phtml by simple code in Magento 2

Suppose We have a code as below in any custom module Block file or In any default Vendor Magento Block file


namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;

class Main extends Template
{
public function getMyCustomMethod()
{
return '<b>I Am From MyCustomMethod</b>';
}
}

Sometime we need to call a function from Block file in phtml file. So, we can do it by below code


$blockObj= $block->getLayout()->createBlock('Company\Helloworld\Block\Main');
echo $blockObj->getMyCustomMethod();

That’s how you can call any block function in phtml by simple code in Magento 2
I hope it helps you.

Leave a Reply