Re: 2 errors I can not understand

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, March 13, 2007 6:04 pm, Jonathan Kahan wrote:
> This did fix the problem but I am amazed that
>
> $s%$d=0 would be interpereted as a statement assigning d to 0 since
> there is
> some other stuff in front of d... I would think that would produce an
> error
> at compile time since $s%$d is an illegal variable name. Normally when
> my
> php script errors at compile time nothing will display to the screen.

You still have not correctly puzzled out what $s % $d = 0 is doing...

The = operator takes precedence, and $d is set to 0.

*THEN* $s % 0 is calculated, and, err, whatever $s % 0 is, that's the
answer you get...  Danged if I know what $s % 0 is, as it's kind of
meaningless, really...

But that is what happens.

There *ARE* cases where it is handy to use an assignment and take the
result of that operation, and use it as part of a bigger expression,
however.

Suppose, for example, that instead of is_prime your wrote a function
has_divisor(), and it returned 0 for prime numbers, and a divisor for
non-prime:

2 => 0
3 => 0
4 => 2
5 => 0
6 => 2
7 => 0
8 => 2
9 => 3

You could write this very much like your current is_prime, only a bit
different. :-)

if ($result = is_prime($k)){
  echo "$k is divisible by $result, so is not prime<br />\n";
}
else{
  echo $k is prime<br />\n";
}

Here we are using the result of the assignment as our test expression
for the if(), killing two birds with one stone.

It's a little bit puzzling at first, but is "clear enough" to
experienced developers that the idiom has taken hold, and is quite
common.

Some folks don't like it, and won't use it, mind you, but it shouldn't
freak you out when you see it either. :-)

-- 
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some starving artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux