开发者

php function __construct() question involving this->get = $_GET

I'm working on someone's code and they have a constructor that uses:

class qwerty {
public function __construct(){
// some other code
    $this->get = $_GET;
}
}

My question is this: Is it possible to sanitize the data within the constructor? Even using some开发者_StackOverflow中文版 simple function like strip_tags()?

Example of usage:

$qwerty = new qwerty;
qwerty->get['id'];


I see two ways to approach it. One would be to just use a foreach loop in the contructor to loop through the $_GET parameters

foreach($_GET AS $key => $val)
{
  $_GET[$key] = sanitize($val);
}

Alternatively, retrieve the data via a get function and sanitize there.

function getParams($key)
{
  return sanitize($_GET[$key]);
}


You can do pretty much anything you want in the constructor. Having said that, it doesn't mean you should. Many would argue that anything meaningful or that could throw an exception should not be in a constructor. Anyways, If you are going to use this class you could do something like this:

class qwerty
{
    private $get;

    public function __construct($params)
    {
       $this->get = $this->sanitize($params);
    }

    public function sanitize($params)
    {
        $sanitized = $params;

        foreach ($sanitized as $key => $value) {
            $sanitized[$key] = strip_tags($value);
        }

        return $sanitized;
    }

    public function getField($field)
    {
        if (array_key_exists($field,$this->get)) {
            return $this->get[$field];
        } else {
            return null;
        }
    }
}

$q = new qwerty($_GET);
$q->getField('id');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜