gpt4 book ai didi

异常类中的php父构造函数

转载 作者:行者123 更新时间:2023-12-04 05:10:51 24 4
gpt4 key购买 nike

于是又在看PHP手册,看到一个自定义异常调用父异常构造函数的代码的注释,不明白这样做的目的。

这是代码:

class MyException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0) {
// some code

// make sure everything is assigned properly
parent::__construct($message, $code);
}

// custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}

public function customFunction() {
echo "A custom function for this type of exception\n";
}
}

我不明白以下逻辑:
//make sure everything is assigned properly
parent::__construct($message, $code);

关于为什么这样做的任何逻辑都会有所帮助。

最佳答案

异常类包含自己的属性,例如 $code$message
它们受子类的影响,例如:

class Exception {
protected $code ;
protected $message ;

public function __construct($code, $message){
$this->code = $code ;
$this->message = $message ;

//AND some important default actions are performed
//when class is instantiated.
}
}

因此,在您调用 parent::__construct() 之后

您的子类将具有实例变量 $code$message正确设置。
$myEx = new MyException("10", "DB Error") ;
//Now you can get the error code, because it was set in its parent constructor:
$code = $myEx->getCode() ;

关于异常类中的php父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14937582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com