views:

91

answers:

2

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 simple function like strip_tags()?

Example of usage:

$qwerty = new qwerty;
qwerty->get['id'];
+1  A: 

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]);
}
Zurahn
Thanks! that seems to have worked!
kylex
A: 

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');
Chris Kloberdanz