I have an instance of a product object:

$_product = $this->getProduct();

Here is a sample from the product object

object(Varien_Data_Collection)#405 (13) {
  array(1) {
    object(Varien_Object)#394 (7) {
      array(11) {
        string(1) "1"
        string(17) "/h/a/image.jpg"
        string(0) ""
        string(1) "1"
        string(1) "0"
        string(1) "1"
        string(1) "0"
        string(66) "http://domain.domain.domain/media/catalog/product/h/a/image.jpg"
        string(1) "1"
        string(73) "/home/domain/public_html/magento/media/catalog/product/h/a/image.jpg"
      array(0) {
      array(0) {

I want to access the "url" inside the object Varien_Object identified by 1 inside the object Varien_Data_Collection identified by "media_gallery_images". This seems easy enough, right?

$url = $_product->getMediaGalleryImages()->get1()->getUrl();

This echos an error into my source:

<b>Fatal error</b>:  Call to undefined method Varien_Data_Collection::get1() in <b>[filepath]

So I'm getting halfway there, but the magic method get1() isn't working. I don't know enough about how these methods work to understand why.

How I access the element that I want to access (["url"])?


Okay so this works specifically for the url

$url = chop($_product->getMediaConfig()->getMediaUrl($_product->getMediaGallery('images')['file']), "/")  . $_product->getImage();

But honestly there has to be a way to do it how I was trying to originally. That "general" solution would save me from running into problems with this further in development.


Okay, I don't know how nobody could answer this, but I found this solution after I went back to it with a better understanding of magic methods. Here is the solution.

$url = $_product->getMediaGalleryImages()->getItems()[$_product->getId()]->getUrl();

Notice that _items can be accessed with getItems(), then treated as the array that it is. In the example shown above, the product id was 1 (hence the get1() I originally tried).

| improve this answer | |

To add to the accepted answer, the solution works because Varien_Data_Collection::getItems() returns an array.

You could also loop $product->getMediaGalleryImages() until you find the index you're looking for, since Varien_Data_Collection implements IteratorAggregate, and its getIterator() method returns an ArrayIterator of it's items (array):

# File: /lib/Varien/Data/Collection.php
 * Implementation of IteratorAggregate::getIterator()
public function getIterator()
    return new ArrayIterator($this->_items);

Also useful is the ->getItemById() method on the collection to return a specific item from the collection:

$url = $product->getMediaGalleryImages()->getItemById($product->getId())->getUrl();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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