title: Custom error handler to handle errors inside and outside Object code
body: <p>I do know there are already many questions on Stackoverflow related to custom error handlers. But, after reading many of them, as well as the PHP manual, I am still unable to solve my problem. Thus I am posting this question.</p>
  <p>My script is currently structured this way:</p>
  <pre><code>require 'file.php';
  require 'anotherFile.php';
  // several more &quot;require&quot; 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-&gt;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-&gt;run();
  
  // then I may use procedural code again
  doSomethingElse();
  </code></pre>
  <p>My custom error handler is <strong>already</strong> working fine. It catches and processes all PHP errors that occur in the code executed after the error handler is set.</p>
  <h2>My problem:</h2>
  <p>If an error occurs within a method of <code>myObject</code> class, I would like to call a non-static method:</p>
  <pre><code>$obj-&gt;SomethingBadHappened();
  </code></pre>
  <p><code>$obj</code> is not in the scope of <code>myErrorHandler</code>. How can I access <code>$obj</code> inside the error handler to call a member function of <code>$obj</code>?<br />
  I currently have 300KB of PHP code, and I can't change the signature of all the functions to add <code>$obj</code> as a parameter (there are too many functions!).</p>
  <p>I read that it is possible to define the custom error handler as a method of an object. But, if I do that, it won't be able to catch errors that happen before creating the instance of <code>myObject</code> ($obj).</p>
  <p>I also read about exceptions, but it doesn't seem to help solving my problem.
  I am not willing to use global variables. Here are 2 questions that explain why global variables should be avoided:</p>
  <ul>
  <li><a href="https://stackoverflow.com/questions/5166087/php-global-in-functions">PHP global in functions</a></li>
  <li><a href="https://stackoverflow.com/questions/4595964/who-needs-singletons">Who needs singletons?</a></li>
  </ul>