请有人解释使用此类代码时的意外结果:
return getObj() or die('Bye');
当getObj
返回对象时,将返回true
(bool
(而不是对象。
但是如果我这样做:
$obj = getObj() or die('Bye');
return $obj;
将返回该对象。
完整示例:
<?php
echo "before testWrongn";
$ret = testWrong();
var_dump($ret); // obj expected, bool returned
echo "after testWrongn";
echo "n";
echo "before testCorrectn";
$ret = testCorrect();
var_dump($ret); // obj expected, obj returned
echo "after testCorrectn";
function testWrong()
{
return createObj() or die('bye');
}
function testCorrect()
{
$obj = createObj() or die('bye');
return $obj;
}
function createObj()
{
//return false;
return new stdClass();
}
输出:
before testWrong
bool(true)
after testWrong
before testCorrect
object(stdClass)#1 (0) {
}
after testCorrect
我在 php.net 上找不到任何内容,除了一条警告此行为的评论,但没有任何解释。
我也知道这种错误处理方式并不好 - 但这不是问题的重点。
谢谢! :)
or
的优先级低于=
,所以
$obj = getObj() or die();
被解析为好像是
($obj = getObj()) or die();
所以这会将对象分配给$obj()
,然后测试其结果。
但return
是一个声明,而不是一个运算符。它计算其整个参数,因此等效于:
$temp = (getObj() or die());
return $temp;
or
运算符始终返回布尔值,因此getObj()
的真实结果将转换为TRUE
。