[英]Catching Exceptions in OO PHP
我有一个班级的Person
。
我想在脚本中添加错误处理,也就是说,用户输入了一个错误的电子邮件地址,脚本将告诉他们。 通常一点都不是问题,但是现在我在不熟悉的领域中使用OO类。
所以。 我想我想知道如何处理多个异常。 还是我需要一次尝试每一行代码并抓住每一行? 这似乎有点过分。 理想情况下,我想执行以下操作:
try {
$people[$new]->set_fullname($_POST['name']);
$people[$new]->set_active(true);
$people[$new]->set_add1(rEsc($_POST['add1']));
$people[$new]->set_add2(rEsc($_POST['add2']));
$people[$new]->set_add3(rEsc($_POST['add3']));
$people[$new]->set_add4(rEsc($_POST['add4']));
$people[$new]->set_postcode(rEsc($_POST['postcode']));
$people[$new]->set_phone(rEsc($_POST['phone']));
$people[$new]->set_email(rEsc($_POST['email']));
} catch {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
但是在我的错误处理中,如何捕获多个错误? 我想将所有错误消息推送到一个数组中,并在网页中很好地显示它们。 据我在php.net上看到的信息,似乎我一次只能捕获一条错误消息。
我真的必须try {} catch {}
每行代码吗?
恕我直言,这不应首先引发异常。 只需遍历这些字段,然后将可能的错误添加到某些$errors
数组中即可。
用户搞砸领域并非例外。 我什至不认为用户对象应该能够验证电子邮件地址。 这似乎是表格的责任。
我也想知道您正在使用什么rEsc
函数。 不仅您使用的是global
函数,将来几乎不可能将其换成其他函数(紧密耦合),而且名称选择也不正确。 我是否也看不到您为什么要在那个地方逃避某些东西(我想那是该做的事情)。 仅在使用数据时转义/清理数据。 我想知道您要转义的数据是什么,因为如果用于数据库输入,则还有更好的方法。
try {
$people[$new]->set_fullname($_POST['name']);
$people[$new]->set_active(true);
$people[$new]->set_add1(rEsc($_POST['add1']));
$people[$new]->set_add2(rEsc($_POST['add2']));
$people[$new]->set_add3(rEsc($_POST['add3']));
$people[$new]->set_add4(rEsc($_POST['add4']));
$people[$new]->set_postcode(rEsc($_POST['postcode']));
$people[$new]->set_phone(rEsc($_POST['phone']));
$people[$new]->set_email(rEsc($_POST['email']));
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} catch (EmailFormatException $em) {
echo 'Caught exception: '. $e->getMessage();
}
就这样继续吧
这是我的设计方式:
全部放在一起:
class Person {
public $name;
public $address1;
public $address2;
public function validate() { }
}
然后您的代码:
$obj = new Person();
$obj->name = "Bob";
$obj->address1 = "1 Elm St.";
$validationResult = $obj->validate();
if ( $validationResult != null) { // there were errors
print_r($validationResult);
}
您可以制作一个foreach语句,在循环内使用try / catch设置需要验证的数据,以便使用错误填充数组,如下所示:
$errors = [];
foreach (['field1', 'field2', ...] as $field) {
try {
$method = "set_{$field}";
$people[$new]->$method(rEsc($_POST[$field]));
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.