在php中是否可以抛出数组而不是字符串作为异常?
我想在php中抛出一个数组作为异常,而不是字符串。如果您定义自己的类来扩展Exception类,是否可以这样做在php中是否可以抛出数组而不是字符串作为异常?,php,custom-exceptions,Php,Custom Exceptions,我想在php中抛出一个数组作为异常,而不是字符串。如果您定义自己的类来扩展Exception类,是否可以这样做 例如抛出新的CustomException('string',$options=array('params')当然可以。这将取决于您的错误处理代码,并适当地使用数组属性。您可以定义自定义异常类的构造函数以获取所需的任何参数,然后确保从构造函数定义中调用基类的构造函数,例如: class CustomException extends \Exception { private
例如
抛出新的CustomException('string',$options=array('params')代码>当然可以。这将取决于您的错误处理代码,并适当地使用数组属性。您可以定义自定义异常类的构造函数以获取所需的任何参数,然后确保从构造函数定义中调用基类的构造函数,例如:
class CustomException extends \Exception
{
private $_options;
public function __construct($message,
$code = 0,
Exception $previous = null,
$options = array('params'))
{
parent::__construct($message, $code, $previous);
$this->_options = $options;
}
public function GetOptions() { return $this->_options; }
}
然后,在您的呼叫代码中
try
{
// some code that throws new CustomException($msg, $code, $previousException, $optionsArray)
}
catch (CustomException $ex)
{
$options = $ex->GetOptions();
// do something with $options[]...
}
请查看扩展异常类的php文档:
是的,你可以。您需要扩展并创建一个_construct()方法来做您想做的事情。我想我给出答案有点晚了,但我也想分享我的解决方案。可能有更多的人在找这个:)
如果不想扩展异常,可以将数组编码为字符串:
try {
throw new Exception(serialize(['msg'=>"Booped up with %d.",'num'=>123]));
} catch (Exception $e) {
$data = unserialize($e->getMessage());
if (is_array($data))
printf($data['msg'],$data['num']);
else
print($e->getMessage());
}
如果您愿意,也可以使用json\u encode
/json\u decode
。我想我可能有点不舒服。不过,有一个有趣的问题。将true作为第二个参数添加到json_decode将返回一个数组,如果省略一个对象,则返回returnedIt最好使用自定义异常并取消序列化自定义\u构造()中的数据。
try {
throw new Exception(serialize(['msg'=>"Booped up with %d.",'num'=>123]));
} catch (Exception $e) {
$data = unserialize($e->getMessage());
if (is_array($data))
printf($data['msg'],$data['num']);
else
print($e->getMessage());
}