您的位置:首页 > 编程语言 > PHP开发

(四)PHP面向对象理论4---异常和错误处理

2015-08-02 15:02 519 查看
一.异常处理:

1.    PHP异常举例:
<?php
//运行无结果。
$a = null;
try{
$a = 5 / 0 ;
echo $a,PHP_EOL;
}catch(exception $e){
$e->getMessage();
$a = -1;
}
echo $a;
2.详细的异常举例:
<?php
header("Content-type: text/html; charset=utf-8");

class emailException extends exception{

}
class pwdException extends exception{
function __toString(){
return "<div class =\"error\">Exception($this->getCode()):
{$this->getMessage()}
in File:($this->getFile()) on Line:{$this->getLine()}</div>";
}
}

function reg($reginfo =null){
if (empty($reginfo) || isset($reginfo)){
throw new Exception("参数非法");
}
if (empty($reginfo['email'])){
throw new emailException("邮件为空");
}
if ($reginfo['pwd'] != $reginfo['repwd']){
throw new pwdException("两次密码不一致");
}
echo "注册成功";
}
/*
* 这个代码无法执行,抽空找原因
*/

try{
reg(array('email' => 'waitfox@qq.com','pwd'=>123456,'repwd'=>12345678));
}catch (emailException $ee){
echo $ee->getMessage();
}catch (pwdException $ep){
echo $ep;
echo PHP_EOL,"特殊处理";
}catch (Exception $e){
echo $e->getTraceAsString();
echo PHP_EOL,"其他情况统一处理";
}
3.    用到异常处理的场景:

a.    对程序的悲观预测

b.    程序的需要和对业务的关注

c.    语言级别的健壮性要求:捕捉异常并做出相应的补救

3.    面对异常:处理异常需要在合理的场景下
二.PHP的错误级别:

1.PHP的错误级别:

a.deprecated:最低级别。‘不推荐,不建议’

b.notice:语法不当。比如使用变量而未定义

c.warning:函数参数不匹配

d.fetal error:直接导致PHP流程终结,后面代码不再执行。

e.prase error:语法检查阶段将报此错。PHP手册一共定义了16个级别的错误。

2.举例:
<?php
//php5.6,据说可以演示错误,但我出现了正确结果……
$date = '2012-12-20';
if (ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})",$date,$regs)){
echo "$regs[3].$regs[2].$regs[1]";
}else{
echo "Invaild date format:$date";
}

if ($i>5){
echo "$i没有初始化啊",PHP_EOL;
}

$a = array('o'=>2,4,6,8);
echo $a[o];
$result = array_sum($a,3);
echo fun();
echo "错误了…… 能继续吗?";
4.    PHP错误处理机制:
<?php
function customerError($errno,$errstr,$errfile,$errline){
echo "<b>错误代码:</b>[${errno}],文件{$errstr}\r\n";
echo "错误所在的代码行:{$errline}文件{$errfile}\r\n";
echo "PHP版本",PHP_VERSION,"(",PHP_OS,")\r\n";
}

set_error_handler("customeError",E_ALL|E_STRICT);
$a = array('o'=>2,4,6,8);
echo $a['o'];

//此问题亦无答案。没有报错
三.PHP面向对象的总结:

PHP面向对象的知识点:魔术方法、接口、多态、类的复用、反射、异常机制。

PHP也引入了一些函数式编程的概念。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息