If you are inside a phtml file, and you need to call an specific function inside another block. You can do the following :
Step 1 : Create Block file
File Path : app/code/V4U/Helloworld/Block/View.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php namespace V4U\Helloworld\Block; class View extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Backend\Block\Template\Context $context, array $data = [] ) { parent::__construct($context, $data); } public function getHelloWorld() { return 'Hello World'; } public function getCustomMethod() { return 'Hello World (Custom Method)'; } } |
Step 2 : Create template file
File Path : app/code/V4U/Helloworld/view/frontend/templates/view.phtml
1 2 3 |
<h2> <?php echo $block->getCustomMethod(); ?> </h2> |
In another phtml you can call by following way.
1 2 3 4 5 6 |
<?php $blockInstance= $block->getLayout()->createBlock('V4U\Helloworld\Block\View'); echo $blockInstance->myCustomMethod(); ?> |
Step 3: Run the following Magento command :
php bin/magento cache:clean
Happy Coding. Keep Liking & Sharing