Re: Watch out for automatic type casting
| From: | Simon Schick | Date: | Thu, 29 Mar 2012 17:18:44 +0000 |
| Subject: | Re: Watch out for automatic type casting | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-317344@lists.php.net to get a copy of this message | ||
Hi, Arno
FYI: I found a page in the php-manual that's exactly for that:
http://www.php.net/manual/en/language.operators.precedence.php
p.s. some of them were also new to me .... Thanks for getting me to read it..
Bye
Simon
2012/3/29 Simon Schick <simonsimcity@googlemail.com>:
> Hi, Arno
>
> I don't know if this is written somewhere in the php-manual, but I
> really like this table:
>
> http://en.wikipedia.org/wiki/Order_of_operations#Programming_languages
>
> I do not really understand why this has some special stuff to do with
> typecasting ... This is just an order like the operators + and * in
> math.
> If you'd ask me, this is exactly what I would expect to happen.
>
> Bye
> Simon
>
> 2012/3/29 Arno Kuhl <arno@dotcontent.net>:
>> I found automatic typecasting can be a bit of a gotcha.
>>
>>
>>
>> $sText = "this.is.a.test.text";
>>
>> if ( $pos = strpos($sText, "test") !== FALSE) {
>>
>> echo substr($sText, 0, $pos)."<".substr($sText, $pos,
>> strlen("test")).">".substr($sText, $pos+strlen("test"));
>>
>> }
>>
>>
>>
>> The code seems logical enough, and the expected result would be:
>>
>> this.is.a.<test>.text
>>
>>
>>
>> In fact it ends up being:
>>
>> t<his.>is.a.test.text
>>
>>
>>
>> The reason is $pos is typecast as TRUE, not int 10, presumably because it's
>> in the same scope as the boolean test.
>>
>> Then when $pos is later used as an int it's converted from TRUE to 1.
>>
>>
>>
>> You have to bracket the $pos setting to move it into its own scope to
>> prevent it being typecast:
>>
>> if ( ($pos = strpos($sText, "test")) !== FALSE) {
>>
>>
>>
>> No doubt it's mentioned somewhere in the php manual, I just never came
>> across it.
>>
>> Just thought I'd highlight one of the gotchas of auto typecasting for any
>> other simpletons like me.
>>
>>
>>
>> Cheers
>>
>> Arno
>>