开发者

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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜