静态与非静态辅助方法

时间:2012-08-16 07:42:06

标签: php magento

我是PHP和Magento的新手,我正试图找出以下两行之间的区别:

$helper = Mage::helper('catalog/category');

$helper = $this->helper('catalog/category');

我在模板文件中看到了类似的代码,但是何时以及为什么我会使用其中一个而不是另一个?

1 个答案:

答案 0 :(得分:5)

第一行$helper = Mage::helper('catalog/category');正在将对象分配给帮助者。

第二行$helper = $this->helper('catalog/categry');将对象的属性赋给变量 - 但只能在对象中使用,因为它使用$this->语法。

在对象内部通过$this->在外部引用它的属性,通过变量名称引用它,然后引用属性$someVar->

另外需要注意的是,你的第一个语句是(正如Eric正确指出的那样)第一个语句是第一个可以调用静态方法(这是一种可以在不创建实例的情况下运行对象函数的可爱方法对象 - 通常不起作用。)

通常你必须先创建一个对象才能使用它:

class something
{
    public $someProperty="Castle";
    public static $my_static = 'foo';
}

echo $this->someProperty; // Error. Non-object. Using '$this->' outside of scope.

echo something::$someProperty; // Error. Non Static.
echo something::$my_static; // Works! Because the property is define as static.

$someVar = new something();

echo $someVar->someProperty; // Output: Castle
相关问题