我有这个代码
$myvar = is_object($somevar) ? $somevar->value : is_array($somevar) ? $somevar['value'] : '';
问题是有时我会得到这个错误
PHP Error: Cannot use object of type 'mypath'method as array in /var/www/htdocs/website/app/resources/tmp/cache/templates/template_view.html.php on line 988
988行是包括在上面的I行。我已经在检查它的对象或数组了,那么为什么会出现这个错误呢?
这与优先级或PHP评估表达式的方式有关。用括号分组解决了问题:
$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');
请参阅此处的注释:http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
注:
建议您避免"堆叠"三元表达式。PHP在单个运算符中使用多个三元运算符时的行为声明不明显:
示例#3不明显的三元行为
<?php // on first glance, the following appears to output 'true' echo (true?'true':false?'t':'f'); // however, the actual output of the above is 't' // this is because ternary expressions are evaluated from left to right // the following is a more obvious version of the same code as above echo ((true ? 'true' : false) ? 't' : 'f'); // here, you can see that the first expression is evaluated to 'true', which // in turn evaluates to (bool)true, thus returning the true branch of the // second ternary expression. ?>
您需要在第二个三进制:周围放置括号
$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');
这一定与运算符优先级有关,不过我还不确定为什么。
意见:带括号或不带括号的三进制很难阅读IMHO。我会坚持扩展形式:
$myvar = '';
if(is_object($somevar)) {
$myvar = $somevar->value;
} elseif(is_array($somevar)) {
$myvar = $somevar['value'];
}