Re: [PHP] PHP is Zero
[email protected] (Pete Ford)
| Newsgroups | php.general |
|---|---|
| Message-ID | <[email protected]> |
On 13/06/13 08:59, BUSCHKE Daniel wrote:
> Hi all,
> I want to start a discussion about a PHP behaviour that drives me crazy for years. For the beginning I would like you to guess what the result of the following snippet will be:
>
> var_dump('PHP' == 0);
>
> I know the difference of == and === but the result was unexcpected for me. And I hope it is also for you. The result is simply "true". Why is it true? I guess this happens because of the conversion from 'PHP' to a number which will be 0 in PHP. And of course 0 equals 0. There are several points that I just want to drop into this mailinglist to discuss about:
>
> 1. Why? :)
42
> 2. Why is PHP converting the String into a Number instead of converting the Number into a String? (If my guess concerning the behaviour is correct)
Since PHP is a weakly-typed language, it has to choose one way or the
other. The behaviour *is* predictable if you know what the rule is (I'm
sure the order of conversion is documented somewhere).
> 3. Why is PHP throwing data away which has the developer explicit given to the interpreter?
Because PHP is weakly-typed, the developer is not being sufficiently
explicit. Try
php -r 'var_dump(intval('PHP') == 0);'
and
php -r 'var_dump('PHP' == strval(0));'
to see explicit code. Anything less is implicit.
> 4. Why does var_dump(0 == 'PHP'); has the same result as the snippet above? This meens that the equal operator is not explictly implemented in the string or integer?
The rule is consistent: it always converts the string to an integer
whatever the order.
> 5. Thats a bug I have opend: https://bugs.php.net/bug.php?id=51739 where I also had the same problems because "8315e839da08e2a7afe6dd12ec58245d" was converted into float(INF) by throwing everything starting from "da08.." away.
>
That's a very different proposition, and probably has more to do with
word size: float is 32-bit, so only the first 32 bits are used and if
anything else is found the conversion falls back to INF. To handle
really big integers like 8315e839da08e2a7afe6dd12ec58245d you probably
need a more specialist library (or language)
> I am using PHP since the year 2000. This means I have 13 years of experience in PHP and I really would like you to NOT just answer "works as designed". I know it works as designed but I want to discuss the design. Also I know that the "fuzzy" behaviour of type conversion is a main feature of PHP. I guess this is one point which makes PHP that successfull. But - in my opinion - the described behaviour is to fuzzy and just confuses developers.
The weak typing *is* a feature of PHP: other languages are more suitable
when you need more enforcement of types: Java, for example.
With all due respect to an experience programmer, years of experience do
not make up for a limited tool set.
>
> Best Regards
> Daniel Buschke
>
Cheers
Pete