Magento 2 – Difference Between $block and $this

blockslayoutmagento2template

I have block Class Name NameSpace1\Test\Block\Test with method getTest()

namespace NameSpace1\Test\Block;

class Test extends \Magento\Framework\View\Element\Template {
    public function getTest(){
        return "Same Result";
    }
}

My Template file name test.phtml with following code

<h3>Class: <?php echo get_class($block) ?> Result: (<?php echo $block->getTest() ?>)</h3>
<h3>Class: <?php echo get_class($this) ?> Result: (<?php echo $this->getTest() ?>)</h3>

and output the code is following result

enter image description here

my question is what is difference between $this and $block and which is better to use in my template file both have get same result

Best Answer

Regardless of what object in template you use ($block or $this) always will be called method from $block.

Magic happens in \Magento\Framework\View\TemplateEngine\Php::__call().

public function __call($method, $args)
{
    return call_user_func_array([$this->_currentBlock, $method], $args);
}

So \Magento\Framework\View\TemplateEngine\Php is only proxy between template and $block, hence $block usage is preferred because of direct call.

Additionaly check \Magento\Framework\View\TemplateEngine\Php::render() to understand how $block is available in template.

Related Topic