从view.phtml中的类定义中访问产品属性

时间:2015-11-27 10:26:36

标签: magento magento-1.9

我在view.phtml的代码中添加了一个小函数来检查相关产品是否具有某些属性,然后从中构建一个列表。

我的文件顶部有

 <?php $_helper = $this->helper('catalog/output');?>
 <?php $_product = $this->getProduct(); ?>

和我的代码中的其他地方我非常高兴并且毫无问题地使用了这样的调用:

<?php $_product->getColor();?>

到目前为止一切都很精致。

后来我声明了一个类AttributeList,在它的构造函数中我尝试访问$ _product的值

 class AttributeList{  // AttributeList CLASS DEFINITION
   public $attributes = array();    
   public $count;
   function __construct(){ //CONSTRUCTOR FOR AttributeList CLASS
        $this->itemCount = 0;
        if($_product->getColor()){
        //DO SOME THINGS
        }
     }//CONSTRUCTOR ENDS    
   }// AttributeList CLASS ENDS

这导致我的页面无法加载。如果我将if语句的条件更改为任意的,如“0&lt; 1”,则代码执行完美,因此我认为问题是$ _product在我的类定义中是不可见的。

有人可以解释为什么会这样,以及我应该如何从我的班级定义中访问我的产品的属性?

我忽略了magento或php这个愚蠢明显的方面吗?

1 个答案:

答案 0 :(得分:1)

将一个课程放在视图中但回答你的问题是非常糟糕的做法,在课堂上使用Mage::registry('current_product')

<?php
class AttributeList {

    public $attributes = array();    
    public $count;
    public $product;

    function __construct()
    {
        $this->itemCount = 0;
        $this->product = Mage::registry('current_product');

        if($this->_product->getColor()){

        }
    }
}