Nathaniel Wendt
Nathaniel Wendt

Reputation: 1204

Php/Magento comparison operator always returning true?

I am trying to use a simple if comparison and it seems to always render as true.

if ($this->helper('catalog/image')->init($_child_products[$i], 'image') == $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile()) ){
    echo 'true';
}

I know for a fact that these two items are not equal (if you don't know Magento, they are used to get urls for product images in different ways).

I use these methods in

<img src="<?php $this->helper...etc ?>" />

And if I echo them, they are clearly different. Is the comparison somehow comparing whether they exist or not and they are both returning true? If so, how can I make it so it compares them as strings?

Upvotes: 0

Views: 587

Answers (1)

Alana Storm
Alana Storm

Reputation: 166046

Try this

var_dump($this->helper('catalog/image')->init($_child_products[$i], 'image'));
var_dump($this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile());

My guess is each of the above var_dump statements will dump a PHP object to the browser/output-environment, (or cause possibly cause a "memory exhaustion" fatal error if you don't have xDebug installed).

Now try this

var_dump((string) $this->helper('catalog/image')->init($_child_products[$i], 'image'));
var_dump((string) $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile());

You should see your identical strings. The init method returns an object, which means when you're doing your equality check, you're checking for quality on the helper objects. In Magento, objects instantiated as helpers are, effectively, singletons, which means multiple instantiations will return the same object, which is what object equality checks for.

When you cast these objects as strings, (with (string)), PHP converts the object to a string (using the __toString method defined on the object.

When you use an object in "string context" (in an echo or print statement, or somewhere else PHP expects a string), PHP will automatically cast the object as a string.

So if you want to do an equality check, cast the objects as strings first.

if ((string)$this->helper('catalog/image')->init($_child_products[$i], 'image') == (string)$this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile()) ){
    echo 'true';
}

Upvotes: 5

Related Questions