0

i have the following logic in my model:

if ( $switch_obj->connect() )  {
  if ( $data = $switch_obj->showIntAll() )  {
        $switch_obj->disconnect();  
        return $data;
  }
  else  {
     $switch_obj->disconnect();
     throw new Exception('Empty Data Set');
  }
}
else  {                                     
   throw new Exception('Connection');                                  
    }

This switch_obj that's being called has logic in it's constructor and destructor to increment / decrement counters respectively. (saved in a class called testclass). So each time an object of type testclass is instantiated, a counter is increased. And then when destroyed, it's decremented. However, I've just discovered a scenario that I'm not handling.

Fatal error: Call to undefined method testclass::showIntAll() in /var/www/myapp/application/models/test_model.php on line 215

It's clear that I'm calling a method that doesn't exist, which I will resolve. But my question is this: in creating this error, i can see that the counter has already been incremented ... but not decremented because once this error is thrown, it never returns to the destructor method in my class. How would I program for these types of scenarios? Obviously, in production, I won't get getting errors because of missing methods in testclass... but in case I do get an unexpected error where the testclass constructor is called and then it bombs, I'm just wondering what the best way is to handle this.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
dot
  • 14,928
  • 41
  • 110
  • 218
  • "Fatal error" means "something is really really broken". On the one side this means, that there is no rescue at all, on the other side it means, they don't just simply appear. Test your code properly, and there be no fatal errors. In your case: Why do you call this method, when it doesn't exists? – KingCrunch Jan 15 '13 at 14:27
  • @KingCrunch...I don't plan on calling non existent functions. But i used the above example because I was in the process of building a new class when i came across this scenario... I am trying to anticipate unexpected fatal errors in the future and see how to handle them. – dot Jan 15 '13 at 16:16

2 Answers2

2

You might achieve something with register_shutdown_function. Your constructor could register a clean-up function which would get called if an error would occur. You'd have to be careful not to call the clean-up code twice though (once from the destructor and once from this registered function.

Not a pretty solution, but it could work :)

Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
1

As far as i can remember destructors are not called on fatal errors