Is it preferred to assign POST variable to an actual variable?

后端 未结 5 2399
半阙折子戏
半阙折子戏 2021-02-20 18:29

I\'ve just completed my registration form for my website and for the action page where all the SQL takes place I\'ve just skipped assigning the POST variable to actual ones, lik

5条回答
  •  醉酒成梦
    2021-02-20 19:04

    I ran into the same question this very day and I came to conclusion that you should always check if the index exists in order to prevent an "Undefined index" error. If you use the POST data multiple times I would suggest assigning the result of your test to a new variable as you might modify the POST data:

    //at least PHP 7.0.0 required
    $foo = $_POST['foo'] ?? '';
    $bar = $_POST['bar'] ?? '';
    

    Which is aquivalent to:

    $foo = isset($_POST['foo']) ? $_POST['foo'] : '';
    $bar = isset($_POST['bar']) ? $_POST['bar'] : '';
    

    If you only use the POST data once one can skip assigning a new variable and just use $_POST['foo'] ?? '' as argument.

    This solution is based on this excellent answer. Further reading: https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

提交回复
热议问题