Avoid using isset in PHP when accessing $_POST, $_GET, and other variables?

前端 未结 6 1310
北海茫月
北海茫月 2020-12-21 07:06

how can I prevent PHP from returning an Undefined variable error every time I try to check a variable if it has contents and that certain variable hasn\'t b

6条回答
  •  Happy的楠姐
    2020-12-21 07:18

    If you want to set $_POST vars, having a whole lot of these statements really clutters your code:

    if (isset($_POST['info']))
      $info = $_POST['info'];
    ... etc....
    

    How about this?

    function setPostVar( &$v ) {
        $trace = debug_backtrace();
        $vLine = file( __FILE__ );
        $fLine = $vLine[ $trace[0]['line'] - 1 ];
        preg_match( "#\\$(\w+)#", $fLine, $match ); 
        eval("\$v = isset(\$_POST[\"$match[1]\"])?\$_POST[\"$match[1]\"]:'';");
    }
    

    Now, as long as you are happy naming variables similar to your POST vars

    ie. $Foo = $_POST['Foo'];
    

    you can just do this:

    setPostVar($Foo); // equivalent to if(isset($_POST['Foo']) $Foo = $_POST['Foo'];
    setPostVar($Bar); // ditto
    setPostVar($Baz); // ditto
    

提交回复
热议问题