错误对象和数组

时间:2012-07-17 22:56:39

标签: php php-5.3

我有这段代码

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

2 个答案:

答案 0 :(得分: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的   在单个中使用多个三元运算符时的行为   陈述不明显:

  

示例#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.
?>

答案 1 :(得分:3)

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

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

这必须与operator precedence有关,但我不确定为什么。

意见:有或没有括号的三元组很难阅读恕我直言。我坚持使用扩展形式:

$myvar = '';

if(is_object($somevar)) {
    $myvar = $somevar->value;
} elseif(is_array($somevar)) {
    $myvar = $somevar['value'];
}