Php/Magento比较运算符总是返回true


Php/Magento comparison operator always returning true?

我试图使用一个简单的if比较,它似乎总是渲染为真。

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

我知道这两个项目是不相等的(如果你不知道Magento,它们被用来以不同的方式获取产品图像的url)。

我在

中使用这些方法
<img src="<?php $this->helper...etc ?>" />

如果我重复它们,它们显然是不同的。比较是不是在比较它们是否存在,是否都返回真值?如果是,我怎么做才能把它们作为字符串进行比较?

试试这个

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

我的猜测是以上var_dump语句将转储一个PHP对象到浏览器/输出环境,(或者可能导致"内存耗尽"致命错误,如果你没有安装xDebug)。

现在试试

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());

您应该看到相同的字符串。init方法返回一个对象,这意味着当您进行相等性检查时,您正在检查 helper对象的质量。在Magento中,作为helper实例化的对象实际上是单例的,这意味着多个实例化将返回相同的对象,这就是对象相等性检查的目的。

当您将这些对象转换为字符串时,(使用(string)), PHP将对象转换为字符串(使用在对象上定义的__toString方法)。

当你在"字符串上下文中"使用对象时(在echo或print语句中,或者PHP需要字符串的其他地方),PHP会自动将对象强制转换为字符串。

所以如果你想做相等性检查,首先将对象转换为字符串。

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