加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 17:40:34 所属栏目:PHP教程 来源:网络整理
导读:我是 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-getUr
我是 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是类的self,它只在类中用来引用方法或属性,在上面的代码中,没有定义类,为什么它可以直接使用$this关键字? $this-> __(‘Home’)代表什么?

解决方法

既然您标记了这个 magento,那么您可能会有类似 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也是一个关键字和php,但是虽然self实际上是指类,$this指的是一个类的实例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读