What’s the right way to send user input to a class?
Foo class:
<?php
class Foo
{
private $_bar;
private setBar($bar)
{
$this->_bar = $bar;
}
}
?>
Using foo class…
<?php
$foo = new Foo();
$foo->setBar((int) $_POST['input']);
?>
Or should I do the following?
Foo class:
<?php
class Foo
{
private $_bar;
private setBar($bar)
{
$this->_bar = (int) $bar;
}
}
?>
Using foo class…
<?php
$foo = new Foo();
$foo->setBar($_POST['input']);
?>
Should I convert data inside of the get method or pass data to classes already converted? What’s the best approach? Why?
Better yet would be to validate by an exception. If you add another method like:
and someone uses the class like this:
To avoid mishaps like these, I write setters similar to this:
Arguments against #1: user might not include
(int)and therefor data with the wrong type is set in the object.Arguments against #2: (see example above). PHP is translating a string to
0if used while calculating. That means you probably will get an error without even knowing about it until you check the results.