开发者

Is this a bug or am I wrong?

开发者 https://www.devze.com 2023-02-14 01:53 出处:网络
/** * Returns nodes found by xpath expression * * @param string $xpath * @return array */ public function getXpath($xpath)
/**
 * Returns nodes found by xpath expression
 *
 * @param string $xpath
 * @return array
 */
public function getXpath($xpath)
{
    if (empty($this->_xml)) {
        return false;
    }

    if (!$result = @$this->_xml->xpath($xpath)) {
        return false;
    }

    return $result;
}

This code is taken from Magento. You can checkout the specif开发者_StackOverflowic file in their public svn:

http://svn.magentocommerce.com/source/branches/1.5/lib/Varien/Simplexml/Config.php

Now I think that (!$result = @$this->_xml->xpath($xpath)) can never ever evaluate to true and thus the return false statement can never happen.

Because the assignment of the return value of xpath, regardless of whether it is true or false to the variable $result always returns true and negated always returns false.

So this is a bug or a completely redundant code, or am i wrong?

FYI: I am currently debugging a problem where some config elements get "lost" and I assume the error is somewhere in there.


This is a weird way of building a condition like that, but I think it makes sense.

$result = will assign the result of the xpath operation to $result.

If that result is false (a value which xpath() will return in case of an error), the condition will match and the function will return false.


"Because the assignment of the return value of xpath to the variable $result always returns true" this statement is wrong and I have no idea why did you make this conclusion. Value of assignment operator is always equal to value that was assigned, so it can easily be false or true (($x = false) == false )


You can test that with

var_dump(!$result = FALSE);    // TRUE
var_dump(!$result = array());  // TRUE
var_dump(!$result = array(1)); // FALSE

So if SimpleXml::xpath returns an empty array or FALSE, the Magento function will return FALSE. Negating an array will typecast it to boolean first. Empty Arrays typecasted to Boolean will be FALSE. Which means, when your XPath is syntactically correct, but did not find any results, Magento will return FALSE.


I find it helps to parenthesise the inner assignment like this:

if (! ($result = @$this->_xml->xpath($xpath)) ) {

Visually the assignment is now a sub-task and must be executed before being inverted. Without the extra parentheses it performs exactly the same, this just helps your own code reading.

Any assignment command returns the value being returned. This lets you do things like:

$a = $b = $c = $d = $e = 'A made-up value';

The new value of $e is being returned to $d, which is being returned to $c, and so on...

0

精彩评论

暂无评论...
验证码 换一张
取 消