Search code examples
phpxmlsimplexmlfile-exists

Returning XML value in function


I have a function that returns

if (file_exists($address)) {

    return simplexml_load_file($address) or die("Error loading XML");
}
else {

    return false;
}

Then on my pages I call my XML function

$page = fetchXML();

echo $page->title;

But I get

Notice: Trying to get property of non-object in [...]

When I var_dump($page); I get bool(true)

Why isn't it returning my XML data?


Note:

If I

return $address

in my function, then use

$page = simplexml_load_file(fetchXML()) or die("Error loading XML");

echo $page->title;

it works.


Solution

  • Because you shouldn't shortcircuit it like that:

    $ php -r'function foo(){ return 2 or false; } var_dump(foo());'
    bool(true)
    

    return has less precedence then the or so to speak (actually, it's not an operator, so the whole expression is run), but = has a higher one.

    $page = simplexml_load_file(fetchXML()) or die("Error loading XML");
    

    Is the same as:

    ($page = simplexml_load_file(fetchXML())) || die("Error loading XML");
    

    While

    return simplexml_load_file($address) or die("Error loading XML");
    

    Is the same as:

    return (simplexml_load_file($address) or die("Error loading XML"));
    

    See also operator precedence