【发布时间】:2011-04-04 08:54:41
【问题描述】:
我正在尝试了解 PHP 中异常的使用。它们是如何工作的以及何时使用它们...下面的基本结构是正确的方法。对我来说似乎有些臃肿?
提前感谢您的任何建议或帮助..
<?php
class APIException extends Exception
{
public function __construct($message)
{
parent::__construct($message, 0);
}
public function __toString()
{
echo('Error: ' . parent::getMessage());
}
public function __toDeath()
{
die("Oops: ". parent::getMessage());
}
}
?>
<?php
require_once('exception.class.php');
class auth extends base
{
/*
* User functions
*/
public function user_create($args='')
{
try
{
if ( !isset($arg['username']) || !isset($arg['password']) ||
!isset($arg['question']) || !isset($arg['answer']) )
{
throw new APIException('missing variables, try again');
}
}
catch (APIException $e)
{
$e->__toString();
}
try
{
if ( $this->user_exists() )
{
throw new APIException('user already exists');
}
}
catch (APIException $e)
{
$e->__toString();
}
}
protected function user_exists($name)
{
// Do SQL Query
try
{
$sql = "select * from user where username='$user'";
if (!mysql_query($sql))
{
throw new APIException('SQL ERROR');
}
}
catch (APIException $e)
{
$e->__toDeath();
}
}
}
?>
【问题讨论】:
标签: php class exception-handling