하나. 예외 처리:
1. PHP 예외 예:
<?php //运行无结果。 $a = null; try{ $a = 5 / 0 ; echo $a,PHP_EOL; }catch(exception $e){ $e->getMessage(); $a = -1; } echo $a;
<?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,"其他情况统一处理"; }
<?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 "错误了…… 能继续吗?";
<?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']; //此问题亦无答案。没有报错