开发者

foreach $_POST.. is this bad?

开发者 https://www.devze.com 2023-02-11 14:38 出处:网络
Is it bad practice to use use a foreach to make an array of all post data vs defining exactly what posts you are accepting?

Is it bad practice to use use a foreach to make an array of all post data vs defining exactly what posts you are accepting?


class Foo { 

    function __construct()
    {
        foreach($_POST as $key => $var)
        {
            $this->post[] = $key = $var;
        } 
    }

    function bar()
    {
        echo $this->post['postdata'];
    }

}       

vs;


class Foo { 

    function __construct()
    {
        $th开发者_开发问答is->post = array(
          "postdata" => $_POST['postdata']
        );
    }

    function bar()
    {
        echo $this->post['postdata'];
    }

}       


There is no great harm in automatically processing all of POSTed fields, as long as that processing is limited to storing in a hash. Matter of fact, it can make fore a significantly easier to maintain code.

The moment you start doing something (especially system related) with that data, you need to validate.


The only really bad practice I can find in this code is use of a global state/data. Your objects should never relay on a outside data. It's better to pass this data to the object as a method argument:

 __construct(array $post) {
     foreach (...) {

     }
 }

 new Abc($_POST);

And returning to your question... More strict validators are usually better, however it always depends on what you're trying to achieve. You could define a list of expected elements and throw an exception when some extra element is being found.

0

精彩评论

暂无评论...
验证码 换一张
取 消