为什么模板可以直接使用$ this关键字? [英] Why can a template use $this keyword directly?
问题描述
我是PHP的新手;今天,我在Magento top.phtml
中看到了以下代码.
I am a newbie at PHP; today I see some code as the following in Magento top.phtml
.
<?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 ?>
我知道$this
是class
的自身,它仅在类中用于引用方法或属性,在上面的代码中,没有定义类,为什么可以使用$ this关键字直接? $this->__('Home')
代表什么?
I know $this
is the self of the class
, it's only used in the class to refer to the method or property, on the above code, there is no class has been defined, why it can use $this keyword directly? What does $this->__('Home')
stand for?
推荐答案
因为您已标记此 magento ,您可能拥有类似Mage_Catalog_Block_Navigation
.至少,这些方法暗示了这一点.现在,我对Magento一无所知,但是该类从Mage_Core_Block_Template
扩展而来,在该类中您具有fetchView
方法
Since you tagged this magento you likely have a class like Mage_Catalog_Block_Navigation
. At least, the methods hint at that. Now, I have no clue about Magento, but this class extends from Mage_Core_Block_Template
and in that class you have the fetchView
Method, which at some point does
include $includeFilePath;
当您在方法内 include
代码时,您确实可以访问包含文件中的$this
代码,因为它是在该实例的范围内评估的:
When you include
code inside a method, you do have access to $this
in the included file code, because it is evaluated in the scope of that instance:
包含文件时,文件包含的代码将继承发生包含的行的变量范围.从那时起,调用文件中该行上可用的任何变量将在被调用文件中可用.但是,包含文件中定义的所有函数和类都具有全局作用域.
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
一般示例:
class Template
…
public function render($templateFile)
{
include $templateFile;
}
public function ___($stringToTranslate)
{
// translates $stringToTranslate somehow
}
}
请注意,"$this
不是类的self
"仅部分正确. self
也是关键字和php,但是self
实际上是指类,而$this
是指类的实例.
Note that "$this
is not the self
of the class" is only partially correct. self
is also a keyword and php, but while self
really refers to the class, $this
refers to the instance of a class.
这篇关于为什么模板可以直接使用$ this关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!