News Archive
PhpRiot Newsletter
Your Email Address:

More information

Play nice when extending \Exception

Note: This article was originally published at Planet PHP on 29 May 2011.
Planet PHP

This is just a short follow up to a recent tweet of mine. I have seen this repeatedly happen, even to top notch and usually very careful developers (*). I am not sure why this mistake happens so frequently, but quite often you see code that changes the parameter order for custom Exception constructors. I guess it's mostly because in these cases the developer wants to pass some magic parameters that contain the message (and potentially also the code). Another scenario is adding a new required parameter. In both cases don't! Thanks.

class FooException extends Exception { private $mustBeSet; /** * Please never do this! */ public function __construct($mustBeSet, $message, $code = null) { $this-mustBeSet = $mustBeSet; parent::__construct(message, $mustBeSet-getCode()); } } ?

I guess if you really want to make the given parameter non optional, or do not want to have to pass a message and/or code, then use a factory method.

class FooException extends Exception { public function getInstance(Bar $bar) { return new self($bar-getMessage(), $bar-getCode()); } } ?

Why do I care? I don't want to have to guess what the order is for standard stuff. Also its just a "OO no-no" since classes inheriting should not break the "is a" relation with their parents.

(*) Actually the above applies to any class and method really. I have been guilty of mucking with the signature of methods when using inheritance all the way back in my MDB/MDB2 days, where IIRC I was messing with the signatures when inheriting the PEAR_Error class. So not trying to be a smart ass, just sharing painful experiences :)