Dan*_*iel 6 php oop validation
编写我的第一个PHP类并遇到一个问题,以下是我的__construct
方法:
public function __construct($foo,$bar) {
$this->foo = $foo;
$this->bar = $bar;
}
Run Code Online (Sandbox Code Playgroud)
这两个$foo
和$bar
是必需的,没有他们,该方法将无法正常工作.当对象被实例化时没有定义它们就可以了:
$var = new Class();
Run Code Online (Sandbox Code Playgroud)
因为这会引发异常(例如,Class需要2个参数,没有设置).但如果它们被设置但不是正确的类型,如下所示:
$var = new Class('33','ddd');
Run Code Online (Sandbox Code Playgroud)
我的方法将失败,因为变量的类型错误.
我应该在哪里验证这些?在构造函数或每个方法中?
我现在使用的解决方案现在有效,但我不确定它是否正确:
// $foo needs to be a string with letters only
// $bar needs to be an integer
public function __construct($foo,$bar) {
$this->foo = $foo;
$this->bar = $bar;
if(!is_numeric($bar)){
// Throw exception
}
elseif(other validation case)
etc...
}
Run Code Online (Sandbox Code Playgroud)
面向对象编程的概念对我来说是一个新手,因此非常感谢您对任何参考资料的链接.
Gor*_*don 18
我可能会做这样的事情来防止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;
}
…
Run Code Online (Sandbox Code Playgroud)
这具有额外的优势,如果您以后需要公开公开setter,则只需更改visibility关键字即可.
对它自己的方法进行验证并不是绝对必要的,但我认为它使代码更具可读性.如果您发现该类中的另一个属性需要相同的验证,您也可以更轻松地重用它.
归档时间: |
|
查看次数: |
3894 次 |
最近记录: |