问题描述
我是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:
一般示例:
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关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!