|
Posted by Rik on 05/27/06 15:33
Jerry Stuckle wrote:
> Rik G. wrote:
>> Coming from an Assembler/C/C++/C# background I got to say this is
>> butt ugly:
>>
>> <?php
>> echo "2 + 2 = " . 2+2; // This will print 4
>> echo "2 + 2 = " , 2+2; // This will print 2 + 2 = 4
>> echo "test " . 2+2; // This will print 2
>
> Not if you understand precedence. Remember, '.' has a high
> precedence. The following all work:
>
>
> <?php
> echo "2 + 2 = " . (2+2); // This will print 2 + 2 = 4
> echo "2 + 2 = " , (2+2); // This will print 2 + 2 = 4
> echo "test " . (2+2); // This will print test 4
Not only precedence, type juggling also plays a major part here.
Detailed:
>> echo "2 + 2 = " . 2+2; // This will print 4
1. The string "2 + 2 = " becomes "2 + 2 = 2" (indeed precedence).
2. Trying to add a number to this string casts it to 2 (the first number),
and adds 2, so gives 4.
>> echo "2 + 2 = " , 2+2; // This will print 2 + 2 = 4
The string "2 + 2 = " gets echoed seperately from the integer resulting from
adding 2+2
>> echo "test " . 2+2; // This will print 2
1. The string "test " becomes "test 2".
2. Trying to add the number 2 to "test 2" casts the string to an integer
(0), and adding 2 gives indeed 2
Variable variables, without strict type, are a blessing in some cases, in
others it's immensely irritating. You just have to keep an eye on it :-).
Reading material:
http://nl3.php.net/manual/en/language.types.type-juggling.php
http://nl3.php.net/manual/en/language.operators.php
Table 15-1
When in doubt, cast the piece of code to a certain type by (type) (e.g.
(bool), (string), (int) etc.).
Grtz
--
Rik Wasmus
[Back to original message]
|