【发布时间】:2012-09-09 17:20:28
【问题描述】:
我知道 Stackoverflow 上已经有很多与自定义错误处理程序相关的问题。但是,在阅读了其中的许多内容以及 PHP 手册之后,我仍然无法解决我的问题。因此我发布了这个问题。
我的脚本目前的结构是这样的:
require 'file.php';
require 'anotherFile.php';
// several more "require" here. These files contain many functions
function myErrorHandler($errno, $errstr, $errfile, $errline, $errcontext){
// some code to handle errors here
}
class myObject {
function __construct() {
// set the values here
}
function computeSomething() {
...
doFunction2();
...
}
function SomethingBadHappened()
{
}
}
function doFunction1() {
// for some reason, an error happens here
// it is properly handled by the current error handler
}
function doFunction2() {
// for some reason, an error happens here
// since it got called by $obj, I want the error handler to run $obj->SomethingBadHappened();
// but $obj is not known in myErrorHandler function!
}
set_error_handler('myErrorHandler');
// some procedural code here
doFunction1();
doAnotherThing();
// then I use objects
$obj = new myObject();
$obj->run();
// then I may use procedural code again
doSomethingElse();
我的自定义错误处理程序已经工作正常。它捕获并处理设置错误处理程序后执行的代码中发生的所有PHP错误。
我的问题:
如果myObject类的方法发生错误,我想调用一个非静态方法:
$obj->SomethingBadHappened();
$obj 不在myErrorHandler 的范围内。如何在错误处理程序中访问$obj 以调用$obj 的成员函数?
我目前有300KB的PHP代码,无法更改所有函数的签名以添加$obj作为参数(函数太多了!)。
我读到可以将自定义错误处理程序定义为对象的方法。但是,如果我这样做,它将无法捕获在创建 myObject ($obj) 的实例之前发生的错误。
我还阅读了有关异常的信息,但它似乎无助于解决我的问题。 我不愿意使用全局变量。这里有 2 个问题解释了为什么应该避免使用全局变量:
【问题讨论】:
标签: php oop error-handling procedural-programming