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

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条)

相关推荐 更多相似问题