5

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

  • 1
    Always use $block is given the current class properties – Amit Bera Jan 21 '17 at 10:52
  • @AmitBera both classes get same results want to know the difference – Arshad Muhammad Jan 21 '17 at 11:12
7

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.