RE: [PHP] Re: Looking for caveats to the following code

2006-08-18 Thread Ford, Mike
On 17 August 2006 23:28, Adam Zey wrote:

 
 Better to do this:
 
 if ( ($result = do_something('hello')) !== false )
 {
// do something with $result
 }
 else
 {
// do some other stuff
 }
 
 The result of an assignment like $result = do_something('hello') is
 itself the result you assigned, so you can still compare on that. The
 reason I put it in more brackets was just for readability. I
 don't think
 you actually need the extra set, but I'm not sure.

Of course you do -- without them, it's the equivalent of:

if ( $result = (do_something('hello') !== false) )

which will only assign TRUE or FALSE to $result.

Cheers!

Mike

-
Mike Ford,  Electronic Information Services Adviser,
Learning Support Services, Learning  Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Headingley Campus, LEEDS,  LS6 3QS,  United Kingdom
Email: [EMAIL PROTECTED]
Tel: +44 113 283 2600 extn 4730  Fax:  +44 113 283 3211 


To view the terms under which this email is distributed, please go to 
http://disclaimer.leedsmet.ac.uk/email.htm

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: Looking for caveats to the following code

2006-08-17 Thread Adam Zey

Chris W. Parker wrote:

Hello,

While experimenting with some object stuff I stumbled upon something new
(although not object related).

Normally I would do this:

?php

function do_something($input)
{
  if($input == 'hello')
  {
return $input;
  }
  else
  {
return false;
  }
}

$result = do_something('hello');

if($result !== false)
{
  // do something with $result
}
else
{
  // do some other stuff
}

?


Using the same function above I discovered I can do this:

?php

if($result = do_something('hello'))
{
  // do something with $result
}
else
{
  // do some other stuff
}

?

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).

Thoughts?


Chris.


Better to do this:

if ( ($result = do_something('hello')) !== false )
{
  // do something with $result
}
else
{
  // do some other stuff
}

The result of an assignment like $result = do_something('hello') is 
itself the result you assigned, so you can still compare on that. The 
reason I put it in more brackets was just for readability. I don't think 
you actually need the extra set, but I'm not sure.


Regards, Adam Zey.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php