Difference of using $this and $block in Magento 2 template

One new thing I found in Magento 2 is the usage of object $block in phtml template to get the block method, instead of using $this as we did in Magento 1.

Let’s say we have this method getFoo() in our block:

 

then we can call the method from our template with:

and surely will outpout “here is Foo“.

Now, let’s call the method using object  $this:

and… it turns out that its output still the same: “here is Foo“. WHY??

If we see class type of those objects:

 

As you can see, the block Leogent\Blog\Block\Myblock is not a subclass of Magento\Framework\View\TemplateEngine\Php. But why object $this can call the method of  $block?
The tricks lies within  file Php.php. At line 80 you’ll find this magic function __call:

 

because of this magic function, then any undefined method that called from $this will be evaluated in function __call(), which in turn will call the real method from block $this->_currentBlock (in this case: Myblock).

This is also explaining why we couldn’t call protected functions of the block from our view. The function must be  public.

Conclusion:

all public functions exist in $block will be alsa callable from $this. However, using $this in Magento 2 template is not recommended. It’s better to stay using  $block.

Leave a Reply