Asim Zaidi
Asim Zaidi

Reputation: 28294

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?

Upvotes: 2

Views: 77

Answers (2)

No Results Found
No Results Found

Reputation: 102765

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

Upvotes: 4

Bailey Parker
Bailey Parker

Reputation: 15905

You need to place parenthesis around the second ternary:

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

This must have something to do with operator precedence, though I'm not sure why yet.

Opinion: The ternary with or without parenthesis is difficult to read IMHO. I'd stick with the expanded form:

$myvar = '';

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

Upvotes: 3

Related Questions