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

2 番目の 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'];
}
于 2012-07-17T23:01:36.463 に答える