4
4
4sadly2020-05-28 00:10:12
PHP
4sadly, 2020-05-28 00:10:12

PHP! or === null?

We need to check the $error variable for errors, which is better: or ?
if($error === null){}
if(!$error){}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maksim Fedorov, 2020-05-28
@4sadly

if($error === null){}preferred (sometimes mandatory by standards), because the option if(!$error){}is auto-cast to bool:

  • e.g. 0 will be cast to false, while it could be a valid int value
  • an empty array - it can also be a valid value, but with !$arr it will be converted to false ... of course, allowing both [] and null in the program is as rare as possible, but this can happen

!$anycan be used comfortably when you (and the program) are sure that you are working with either an object or a bool

R
rPman, 2020-05-28
@rPman

If possible, change the type of the return value, i.e. Call the special class Error and check the type of the result after the call.
There is also the practice of removing the error status from the returned value, since errors are different and require different responses, using exceptions - descendant classes of Exception
In this case, each error variant must be caught in its catch section and the call in try (initialize the error itself with using throw).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question