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

后端 未结 4 1231
说谎
说谎 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条回答
  •  不知归路
    2021-02-07 01:01

    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:

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

    Then, in your calling code...

    try 
    {
       // some code that throws new CustomException($msg, $code, $previousException, $optionsArray)
    }
    catch (CustomException $ex)
    {
       $options = $ex->GetOptions();
       // do something with $options[]...
    }
    

    Have a look at the php docs for extending the exception class:

    http://php.net/manual/en/language.exceptions.extending.php

提交回复
热议问题