你能在 php 中抛出一个数组而不是字符串作为异常吗?
我想在 php 中抛出一个数组作为异常,而不是字符串。如果您定义自己的类来扩展 Exception 类,是否可以做到这一点?
例如抛出 new CustomException('string', $options = array('params'));
I want to throw an array as an exception in php, instead of a string. Is it possible to do this if you define your own class that extends the Exception class?
For example throw new CustomException('string', $options = array('params'));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然。这仅取决于您的错误处理代码要注意的问题,并适当地使用数组属性。您可以定义自定义异常类的构造函数来获取所需的任何参数,然后确保从构造函数定义中调用基类的构造函数,例如:
然后,在您的调用代码中...
查看 php 文档用于扩展异常类:
http://php.net/manual/en/language.exceptions.extending。 php
Sure. It will just be up to your error handling code to be aware of, and make use of the array property appropriately. You can define your custom exception class's constructor to take any parameters you want, and then just be sure to call the base class's constructor from within the constructor definition, eg:
Then, in your calling code...
Have a look at the php docs for extending the exception class:
http://php.net/manual/en/language.exceptions.extending.php
我想我的答案有点太晚了,但我也想分享我的解决方案。可能还有更多人在寻找这个:)
I think I'm a bit too late with an answer, but I wanted to share my solution as well. There are probably more people looking for this :)
如果您不想扩展 Exception,可以将数组编码为字符串:
如果您愿意,还可以使用
json_encode
/json_decode
。If you don't want to extend Exception, you can encode your array into a string:
You can also use
json_encode
/json_decode
if you prefer.是的,你可以。您需要扩展 Exception 类 并创建一个 __construct() 方法做你想做的事。
Yes, you can. You will need to extend the Exception class and create a __construct() method to do what you want.