Validating constructor parameters, making sure parameters have the correct type
I'd probably do something like this to prevent clutter inside the ctor and to allow the class to set them values internally:
class MyClass …
protected $_foo;
/**
* @param String $foo String with letters only
* @param Integer $bar Any Integer
* @return void
* @throws InvalidArgumentException when $foo is not letters only
* @throws InvalidArgumentException when $bar is not an Integer
*/
public function __construct($foo, $bar)
{
$this->_setFoo($foo);
$this->_setBar($bar)
}
/**
* @param String $foo String with letters only
* @return void
* @throws InvalidArgumentException when String is not letters only
*/
protected function _setFoo($foo)
{
if (FALSE === $this->_consistsOfLettersOnly($foo)) {
throw new InvalidArgumentException(
'$foo should consists of letters only'
);
}
$this->_foo = $foo;
}
…
This has the added advantage that if you need to publicly expose the setters later, you just have to change the visibility keyword.
Making the validation into it's own method is not strictly necessary, but I think it makes the code more readable. If you find another property in that class needs the same validation, you can also reuse it more easily.
Validating the types in the constructor (as per your example) seems the logical choice to me, although it's a bit odd if the arguments are optional. You should probably set safe defaults if this is case via...
public function __construct($foo=null, $bar=null)
That said, you can use type hinting for arguments in PHP, but I believe this only works for arrays and classes. (Not a surprise, as there's no such thing as an integer or string type in PHP.)
As others have said, you should also ensure that you carry out validation in any setters you have or (better still) simply call the setters from within the constructor to ensure there's no duplication of code.