Re: Exceptions for method on non-object rather than fatal (desired feature?)

From: Date: Wed, 22 Feb 2012 18:04:18 +0000
Subject: Re: Exceptions for method on non-object rather than fatal (desired feature?)
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-57954@lists.php.net to get a copy of this message
On 2/21/12 5:45 PM, Tjerk Meesters wrote:
On 22 Feb, 2012, at 2:03 AM, Ralf Lang<lang@b1-systems.de> wrote:
I see no reason why it would be not desirable to have PHP raise the exception rather than putting more or less repeating code snippets all around the place. That is why I am asking.
You must be returning false/null somewhere. It's the same effor to instead throw an exception or to return a Ghost family member.
The $baby->mother() method cannot know if the using code just wants to collect the $mother object or execute code on it. It can also not know if having no $mother is a problem or just a fact to deal with. Unconditionally raising an exception is a bit overkill here, at least if we would get an exception for trying to access (null)->mother(); Currently the user code must check each link of the chain if it is available, although it is only interested if it can get the final result or not. I'll follow the suggestion and write an RFC.
You'll have my vote! :) bloating code with chainable checks is just crazy, something that the engine can do much more efficiently and unambiguously.
I would also support this. There's a myriad reasons why something may return NULL or FALSE when you expect it to return an object, some of them even legitimate. Any function/method whose documentation line is "returns the foo object, or NULL if someone screwed up and there isn't one" is perfectly reasonable in many cases, IMO, but makes all chains a potential fatal. An exception would make a lot more sense, and allow us to centralize handling of such "exceptional" cases rather than throwing if-checks everywhere. (Which is exactly what exceptions are for.) --Larry Garfield

« previous php.internals (#57954) next »