Proper way to declare multiple vars in PHP

后端 未结 7 1836
清歌不尽
清歌不尽 2021-01-31 01:48

I\'ve been coding personal scripts for years in PHP and get used to turn off Error display. I\'m about to release some of these scripts and would like to do it the proper way.

7条回答
  •  暖寄归人
    2021-01-31 02:26

    Your if() with isset() attempt is the proper way of doing that!

    But you can write it a little bit shorter/more readable, using the Ternary Operator:

    $foo = isset($foo) ? $foo : '';
    

    The first $foo will be set to the value after the ? when the condition after the = is true, else it will be set to the value after the :. The condition (between = and ? ) will always be casted as boolean.

    Since PHP 5.3 you can write it even shorter:

    $foo = isset($foo) ?: '';
    

    This will set $foo to TRUE or FALSE (depending on what isset() returns), as pointed by @Decent Dabbler in the comments. Removing isset() will set it to '' but it will also throw an undefined variable notice (not in production though).

    Since PHP 7 you can use a null coalesce operator:

    $foo = $foo ?? '';
    

    This won't throw any error, but it will evaluate as TRUE if $foo exists and is empty, as opposed to the shorthand ternary operator, that will evaluate as FALSE if the variable is empty.

提交回复
热议问题