Re: Error instead of returning false
| From: | Claude Pache | Date: | Tue, 07 May 2019 15:15:41 +0000 |
| Subject: | Re: Error instead of returning false | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-105630@lists.php.net to get a copy of this message | ||
> Le 7 mai 2019 à 16:22, Gert <gertp93@gmail.com> a écrit :
>
> Hello internals,
>
> I wanted to propose an RFC, but i'd like to check first if this idea
> has been considered before already.
>
> My idea, extremely summarized, would be to take the functions that
> return false/null when they 'error', and instead make them actually
> throw an error.
>
> Currently, functions like getcwd or json_decode will return false/null
> when an error occurs, and they populate a global error state, which
> can be retrieved by error_get_last, or similar functions. json_decode
> already got the JSON_THROW_ON_ERROR option in PHP 7.3, and this RFC
> would basically make that behaviour default. This RFC would target PHP
> 8.0, but i'd like to hear some opinions on this.
>
> Greetings,
> Gert de Pagter (BackEndTea)
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
The big issue, with your proposal, is, of course, migration of legacy code:
<?php
$f = @fopen($whatever);
if ($f === false) {
// handle the error.
}
?>
If you do think that ideally an exception should be thrown here, it is better to devise a new
function—and, while you’re at it, a function that returns an object of some definite class
instead of a resource.
Another issue is that a “failure” is not necessarily an “error”. For example, when I use
strpos(), I expect that it returns sometimes false; and either using a
try/catch construct, or using a separate check beforehand would be cumbersome.
—Claude