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

Accessing product attributes from within a class definition inside view.phtml

我正在为我们的 view.phtml 添加一个小函数来检查相关产品是否具有某些属性,然后根据它们构建一个列表。

在我的文件顶部有

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

在我的代码的其他地方,我很高兴并且没有问题地使用这样的调用:

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

到目前为止一切都很好。

稍后我声明了一个 class 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 < 1”,代码将完美执行,所以我认为问题是 $_product 在我的 class 定义中不可见。

谁能解释为什么会这样,以及我应该如何从我的 class 定义中访问我的产品的属性?

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

将 class 放入视图中是一种非常糟糕的做法,但要回答您的问题,请在 class:

中使用 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()){

        }
    }
}