2

我有这个代码

$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 行是我包含的上述行。我已经在检查它的对象或数组,那为什么会出现这个错误呢?

4

2 回答 2

4

它与优先级或 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 的行为并不明显:

Example #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.
?>
于 2012-07-17T23:01:03.080 回答
3

您需要在第二个三元组周围放置括号:

$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');

这一定与运算符优先级有关,尽管我还不确定为什么。

意见:带或不带括号的三进制很难阅读恕我直言。我会坚持使用扩展形式:

$myvar = '';

if(is_object($somevar)) {
    $myvar = $somevar->value;
} elseif(is_array($somevar)) {
    $myvar = $somevar['value'];
}
于 2012-07-17T23:01:36.463 回答