gpt4 book ai didi

php - 错误对象和数组

转载 作者:行者123 更新时间:2023-12-01 23:36:58 25 4
gpt4 key购买 nike

我有这个代码

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

最佳答案

它与优先级或 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

Note:

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Example #3 Non-obvious Ternary Behaviour

<?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.
?>

关于php - 错误对象和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11531979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com