msvrtan's blog

PHP Fatal errors into exceptions natively

In my last blog post I was writing about fatal error problems when undefined methods do occur. I decided to wait with implementation to see what will other developers say and I was surpised a bit with how much people disagreed with the idea. Tthank you all for feedback here, on twitter and reddit since this got me thinking a little bit more.

If you concept your OO classes on public properties vs. getters/setters your PHP code behaves totally different. Lets say you want to load user 79 and print out a welcome message:

Using getter method that is not implemented will get you fatal error saying how undefined method is called and request will stop.

// Instantiate class.
$objUser = new User();
// Load user.
$objUser->load( 79 );
// Print out username
echo 'Hello ' . $objUser->getName() . '!';

</pre>

On the other hand if you would use public property all you would get is a notice saying how this property does not exist and rest of request would be completed.

// Instantiate class.
$objUser = new User();
// Load user.
$objUser->load( 79 );
// Print out username
echo 'Hello ' . $objUser->name . '!';

</pre>

I know that this is due to dynamic typing behavior of PHP and no I am not suggesting raising a notice if undefined method gets called but since 5.1.0 there is a BadMethodCallException class which would be perfect for this situations. Since I'm not the first one coming with this idea I found a few reports on PHP bug tracker that were closed due to this not being a bug. Since I don't want to spam bug tracker with a copy of already reported and closed issues I was wondering should one of next PHP versions support this as a feature?

If you like the idea please leave a small comment here and if there would be enough interest we could suggest it at PHP RFC Wiki . There are already few similar RFCs but they are not regulating fatal errors ( example ).