Can you throw an array instead of a string as an exception in php?

后端 未结 4 1232
说谎
说谎 2021-02-07 00:22

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 exampl

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 00:53

    If you don't want to extend Exception, you can encode your array into a string:

    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());
    }
    

    You can also use json_encode/json_decode if you prefer.

提交回复
热议问题