我可能会做这样的事情来防止ctor内部的混乱,并允许类在内部设置它们的值:
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;
}
…
这具有额外的优势,如果您以后需要公开公开setter,则只需更改visibility关键字即可.
对它自己的方法进行验证并不是绝对必要的,但我认为它使代码更具可读性.如果您发现该类中的另一个属性需要相同的验证,您也可以更轻松地重用它.