Magento 2 how to call any block function in phtml

Try like this.

Example block is given below

<?php
namespace Company\Helloworld\Block;
use Magento\Framework\View\Element\Template;

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

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

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

Leave a comment

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