Search code examples
phpphp-5.3

error object and array


I have this code

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

issue is that sometime I am getting this error

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

line 988 is the above line I included. I am already checking if its object or array, so why this error then?


Solution

  • It has something to do with priority, or the way PHP is evaluating your expression. Grouping with parentheses solves the problem:

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

    See the notes here: 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.
    ?>