Re: Looking for caveats to the following code
| From: | Jochem Maas | Date: | Fri, 18 Aug 2006 11:11:12 +0000 |
| Subject: | Re: Looking for caveats to the following code | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-240883@lists.php.net to get a copy of this message | ||
Chris W. Parker wrote:
> Hello,
....
>
> <?php
>
> if($result = do_something('hello'))
> {
> // do something with $result
> }
> else
> {
> // do some other stuff
> }
>
> ?>
>
nothing wrong with this. like Adam mentioned you can check the expression to see
if it is exactly false - and if you don't need $result you can also do it like so:
if (do_something('hello') !== false) {
}
or
// some consider this safer because accidentally assigning
// to a literal will cause an error - so you know right away when you made a type
if (false !== do_something('hello')) {
}
to make the 'safety' issue clearer consider these snippets:
if (false == $res) echo "boo!";
if (false = $res) echo "boo!"; // typo with fatal!
if ($res == false) echo "boo!";
if ($res = false) echo "boo!"; // typo with no error but your logic is silently borked!
> The issue is whether or not this is a safe test. My initial thought is
> that it is safe since I'm simply checking for true/false-ness. I either
> check for '!== false' explicitly or (in the case of the latter example)
> check that something other than 'false' is returned.
>
> It's slightly less readable but it seems more efficient (if nothing more
> than to save on the number of lines typed).
readable is probably a question of preference and what your acustomed to; in
situations where you don't need $result you can save on creating a variable by testing
directly on the return result of the given function.
>
> Thoughts?
>
>
> Chris.
>