1

Can someone explain how the image helper works in Magento and if the following two lines are identical? They appear to be identical strings when I run var_dump($temp), but memory usage says otherwise on certain products (outside of the scope of this question, but it happens on certain products and casting the string alleviates the problem).

$temp = $this->helper('catalog/image')->init($product, 'small_image')->resize(135);

$temp = (string)$this->helper('catalog/image')->init($product, 'small_image')->resize(135);

1 Answer 1

4

Those 2 lines are not identical.
After the first line $temp will be an instance of Mage_Catalog_Helper_Image. This is because the resize method returns the currend object.

After the second line $temp will be a string.
When casting an object to a string it's the same as calling $object->__toString();
You can take a look at the Mage_Catalog_Helper_Image::__toString() methods. This is the one that actually creates the cached, resized image if it doesn't exist and returns the url of the image.

About the memory usage, I cant say much. What are you doing with $temp after the lines above? Maybe you do something that reaches the memory limit.

5
  • Ah, does __toStrign() work the same for string-casting inside PHP and when echoing in HTML?
    – laketuna
    Commented Sep 17, 2013 at 20:22
  • Regarding the memory usage, simply assigning $this->helper()->... to a variable allocates ~500MB of memory on certain products. I have a post here: magento.stackexchange.com/questions/8113/…. But I do need to run some more tests to cases.
    – laketuna
    Commented Sep 17, 2013 at 20:24
  • 1
    when calling echo on an object PHP tries to convert it to string so it calls the same __toString method.
    – Marius
    Commented Sep 17, 2013 at 20:27
  • Now I remember about the magic function.. I seem to regularly forget about this. Def need to use need to use OOP more. I see it in Mage_Catalog_Helper_Image where it returns the string URL.
    – laketuna
    Commented Sep 17, 2013 at 20:33
  • if you have to manipulate the url of the cached resized image, like doing a substr match and editing the url, it will be more efficient to cast the helper image object to string. Otherwise every time that substr is called on the object a __toString() is called, which affects performance quite a bit if you do it often.
    – Pitt
    Commented Aug 3, 2016 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.