Why can a template use this keyword directly?

I am new to PHP; Today I see the code in Magento top.phtml as follows.

 <?php $_menu = $this->renderCategoriesMenuHtml(0,'level-top') ?> <?php if($_menu): ?> <div class="nav-container"> <ul id="nav"> <!--NEW HOME LINK --> <li class="home"><a href="<?php echo $this->getUrl('') ?>"><?php echo $this->__('Home') ?></a>"</li> <!--NEW HOME LINK --> <?php echo $_menu ?> </ul> </div> <?php endif ?> 

I know that $this is a self class , it is used only in a class to refer to a method or property, in the above code there is no class, so can it use $ this keyword directly? What does $this->__('Home') mean?

+4
source share
3 answers

Since you checked this magento , you probably have a class like Mage_Catalog_Block_Navigation . At least methods hint at this. Now I have no information about Magento, but this class extends from Mage_Core_Block_Template , and in this class you have a fetchView method that at some point does

 include $includeFilePath; 

When you include inside a method, you have access to $this in the included code of the file, because it is evaluated within this instance:

When a file is included, the code that it contains inherits the scope of the line in which the inclusion occurs. Any variables available on this line in the calling file will be available in the called file from this point forward. However, all functions and classes defined in the included file have a global scope.

General example:

 class Template … public function render($templateFile) { include $templateFile; } public function ___($stringToTranslate) { // translates $stringToTranslate somehow } } 

Note that " $this not a self class" is only partially correct. self also a keyword and php, but while self does refer to the class, $this refers to an instance of the class.

+5
source

The object is defined! This template is used as an instance of a block. This is the instance that is mentioned in the template. A quick way to determine the class that you are currently working with inside the template is to use the following line of code in the template:

 <?php echo get_class($this); ?> 

The __ method is also mentioned. This intercepts the local Magento system. This means that you can write:

 <?php echo $this->__('Hello') ?> 

In your template, use the same template file in the French store and only to create a text mapping from English to French, instead of creating an entire new template.

+1
source

Because this is a template for some block class. The block template ( .phtml file) is included inside the Mage_Core_Block_Template class fetchView() method. You can go to app/code/core/Mage/Core/Block/Template.php and see how it is done. Therefore $this is available in .phtml . You can learn more about the magento block and templates in this Alan Storm article . It is a bit outdated, but the main ones are explained very well (imho).

+1
source

Source: https://habr.com/ru/post/1395900/


All Articles