Maison  >  Article  >  développement back-end  >  PHP example-php encapsule une classe de gestion des exceptions

PHP example-php encapsule une classe de gestion des exceptions

微波
微波original
2017-06-28 12:48:30902parcourir

这篇文章主要为大家详细介绍了php封装一个异常的处理类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

 本文实例为大家分享了php自定义异常处理类,供大家参考,具体内容如下

一、代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>自定义异常处理类</title> 
</head> 
<body> 
<?php 
class TelException extends Exception{      //定义TelException类,继承Exception类 
  public function errorTel(){         //定义方法返回错误信息 
  $errorMsg = "出错原因:".$this->getMessage()."不是一个合法的电话号码"; 
  $errorMsg .="<br>"; 
  $errorMsg .="错误文件路径:".$this->getFile(); 
  $errorMsg .="<br>"; 
  $errorMsg .="错误代码行号:".$this-> getLine();  
  return $errorMsg; 
  } 
} 
function check_tel($tel){              //自定义函数验证电话号码格式是否正确 
  $checkphone="/^13(\\d{9})$/";    //定义验证手机号码的正则表达式 
  $counts=preg_match($checkphone,$tel);      //执行验证操作 
  return $counts;                 //返回验证结果 
} 
$tel = "133891gfj";               //定义被验证的电话号码 
/* 
  通过自定义异常处理类返回错误提示 
*/ 
try { 
  if(check_tel($tel) !=1){ 
    throw new TelException($tel); 
  } 
}catch (TelException $e){ 
  include_once("error.php"); 
} 
?> 
</body> 
</html> 
</body> 
</html>

二、运行结果


Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn