简体   繁体   中英

Static vs. non-static helper methods

I'm new to PHP and Magento and am trying to figure out what the difference is between the following two lines:

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

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

I've seen similar code in the template file, but when and why would I use one instead of the other?

The first line $helper = Mage::helper('catalog/category'); is assigning an object to helper.

The second line $helper = $this->helper('catalog/categry'); is assigning a property of an object to a variable - but can only be used WITHIN the object as it uses the $this-> syntax.

Inside an object refer to it's properties by $this-> while outside, refer to it via the variable name, then the property $someVar-> .

The other thing to note is that your first statement is (as Eric correctly points out) is that the first can be a call to a static method (which is a lovely way to have an object function run without creating an instance of the object - which normally doesn't work).

Normally you have to create an object before you can use it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM