“Wrong parameters for Exception” when creating Exception subclass

筅森魡賤 提交于 2019-12-10 16:46:20

问题


This is my code

class MyException extends Exception
{
   public function __construct($message, $code=0, Exception $previous = null) {
   parent::__construct($message,$code,$previous);
  }
   public function __toString() {
   return __CLASS__. ":[{$this->code}]:{$this->message}\n";
  }
}

Here is the error

Fatal error: Wrong parameters for Exception([string $exception [, long $code ]]) on line 5

means on this line

parent::__construct($message,$code,$previous);

What is going wrong?


回答1:


As noted in the comments, and on the Exception constructor page, the $previous argument was added in PHP 5.3.

This is reflected in the error message:

Wrong parameters for Exception ([string $exception [, long $code ]])

PHP is being a bit zealous in making sure that the constructor matches exactly. Exceptions are an important part of the internal bits, and getting them exactly right is worth being pedantic.

This code demo shows the various ways older PHP versions treat the incorrect parameter count. From the wording used above, you're using PHP 5.1 or 5.2.

Please be aware that at time of writing this (February 2014), versions of PHP prior to 5.4 have reached end of life for security and bug fix updates, and 5.4 is scheduled for EOL in summer 2014.

If you can, please make sure that you're using a modern version of PHP when deploying your application.



来源:https://stackoverflow.com/questions/21684388/wrong-parameters-for-exception-when-creating-exception-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!