Home > Mobile >  PHP message: PHP Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ?
PHP message: PHP Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ?

Time:02-25

I'm having an issue with the piece of code below. I believe I just need to add parentheses but I'm not sure where. Thanks

$host = isset( $s['HTTP_X_FORWARDED_HOST'] ) ? $s['HTTP_X_FORWARDED_HOST'] : isset( $s['HTTP_HOST'] ) ? $s['HTTP_HOST'] : $s['SERVER_NAME'];

CodePudding user response:

although it is often nice to write logic in shorthand, I would personally never sacrifice readability over brevity.

private function getFoo(array $s): string {
    if (isset($s['HTTP_X_FORWARDED_HOST'])) {
        return $s['HTTP_X_FORWARDED_HOST'];
    }

    if (isset($s['HTTP_HOST'])) {
        return $s['HTTP_HOST'];
    }

    return $s['SERVER_NAME'];
}

can also be slightly shorter by doing using the null coalescing operator

private function getFoo(array $s): string {
    if (isset($s['HTTP_X_FORWARDED_HOST'])) {
        return $s['HTTP_X_FORWARDED_HOST'];
    }

    return $s['HTTP_HOST'] ?? $s['SERVER_NAME'];
}

if you do insist on doing the shorthand version, tnavidi's answer is the way to go

CodePudding user response:

I suppose you want it from left to right, so it should be

$host = isset( $s['HTTP_X_FORWARDED_HOST'] ) ? $s['HTTP_X_FORWARDED_HOST'] : (isset( $s['HTTP_HOST'] ) ? $s['HTTP_HOST'] : $s['SERVER_NAME']);

i.e, the latter a ? b : (c ? d : e)-part of the error message

  •  Tags:  
  • php
  • Related