Proper way to declare multiple vars in PHP

后端 未结 7 1838
清歌不尽
清歌不尽 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:15

    A somewhat round-about way of doing this is if you put the name of your variables in an array, and then loop them with a Ternary Operator, similar to powtac's answer.

    $vars = array('foo', 'bar', 'ping', 'pong');
    $defaultVar = '';
    
    foreach($vars as $var)
    {
        $$var = isset($$var) ? $$var : $defaultVar;
    }
    

    As mentioned in other answers, since version 5.3, PHP allows you to write the above code as follows:

    $vars = array('foo', 'bar', 'ping', 'pong');
    $defaultVar = '';
    
    foreach($vars as $var)
    {
        $$var = isset($$var) ?: $defaultVar;
    }
    

    Note the changed Ternary Operator.

提交回复
热议问题