Re: Watch out for automatic type casting
| From: | Maciek Sokolewicz | Date: | Sat, 31 Mar 2012 11:56:27 +0000 |
| Subject: | Re: Watch out for automatic type casting | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-317396@lists.php.net to get a copy of this message | ||
On 30-03-2012 09:47, Arno Kuhl wrote:
-----Original Message----- From: Simon Schick [mailto:simonsimcity@googlemail.com] Sent: 29 March 2012 07:19 PM To: arno@dotcontent.net Cc: php-general@lists.php.net Subject: Re: [PHP] Watch out for automatic type casting 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 ---- Thanks Simon and others, thought it was typecasting, but precedence makes more sense. I remember seeing that table when I first started using php, which is why I always use AND and OR rather than&& and || because it's lower precedence than the assignment and the ternary operators, but I couldn't remember where I'd seen it. So thanks for linking to it. Cheers Arno -- BTW interesting to note on that precedence page that "!" has a higher precedence than "=" (which you'd expect it to be) but you can still do if (!$a = foo()) I use that form often (as I'm sure many others do) and just took it for granted that it works even though the order of precedence says it shouldn't. It could be expanded to if ($a = foo() != TRUE) But that wouldn't get the expected result due to order of precedence, though at first glance you could reasonably expect it to work because of if (!$a = foo()) being valid. I think that's why it's so easy to be caught out (at least for me) by the similar form of if ( $pos = strpos($sText, "test") !== FALSE) Cheers Arno I would still suggest to explicitly supply the precedence you expect. Ie: if(($foo = $var) == true) { }or if($a + (15*$b) ) { } I know you can write it with fewer parentheses, but this at least makes it 100% clear you at all times WHAT is supposed to happen and you're 100% sure that PHP will understand what you WANT it to do aswell instead of having to guess, and fail at it because you don't know how guessing is implemented in the Zend Engine.