duanguan3863 2015-11-02 09:07
浏览 48
已采纳

Magento - 在块模板中未定义变量

I am making a simple magento block and a template for it.

In my custom module I have a config.xml

<?xml version="1.0"?>
<config>
  <modules>
    <AAA_Recentproducts>
      <version>1.0</version>
    </AAA_Recentproducts>
  </modules>
  <global>
    <blocks>
      <recentproducts>
        <class>AAA_Recentproducts_Block</class>
      </recentproducts>
    </blocks>
  </global>
</config>

And this is my Block

<?php
class AAA_Recentproducts_Block_Recentproducts extends Mage_Core_Block_Template {
  public function getRecentProducts() {
    $products = Mage::getModel("catalog/product")
                    ->getCollection()
                    ->addAttributeToSelect('*')
                    ->setOrder('entity_id', 'DESC')
                    ->setPageSize(5);
    return $products;
  }
}

And finally my template file:

<?php
$products = $this­->getRecentProducts();
//$products = [];
?>

<div id="product_list">
  <h1>Recent Products</h1>
  <?php if (is_array($products) && count($products)) { ?>
    <?php foreach($products as $product) { ?>
      <div>
    product
      </div>
    <?php } ?>
  <?php } ?>
</div>

The error I get is: 2015-11-02T08:53:55+00:00 ERR (3): Notice: Undefined variable: this­ in /var/www/html/magento/app/design/frontend/smartwave/granada/template/recentproducts/recentproducts.phtml on line 2

Does anyone have an idea why this error occurs?

  • 写回答

3条回答 默认 最新

  • dongshuobei1037 2015-11-02 09:12
    关注

    You can't use $this if you're not inside a class. You have to create an instance of AAA_Recentproducts_Block_Recentproducts and call the function on that object.

    $object = new AAA_Recentproducts_Block_Recentproducts();
    $products = $object->getRecentProducts();
    

    I wouldn't recommend the variable name $object, but i can't think of a better one right now. You get the point.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!