gpt4 book ai didi

php - 为什么模板可以直接使用 $this 关键字?

转载 作者:可可西里 更新时间:2023-10-31 22:14:30 26 4
gpt4 key购买 nike

我是 PHP 新手;今天我在 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的自身,它只是在类中用来引用方法或属性,在上面的代码中,没有类已经定义了,为什么可以直接使用$this关键字呢? $this->__('Home') 代表什么?

最佳答案

因为你标记了这个 你可能有一个类 Mage_Catalog_Block_Navigation .至少,这些方法暗示了这一点。现在,我对 Magento 一无所知,但是这个类从 Mage_Core_Block_Template 扩展而来,在那个类中你有 fetchView 方法,which at some point does

include $includeFilePath;

当你include方法中的代码,您确实可以访问包含的文件代码中的 $this,因为它是在该实例的范围内计算的:

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 指的是类的实例。

关于php - 为什么模板可以直接使用 $this 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9239269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com