|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-07-29 10:31 UTC] mkrasuski at infico dot pl
Description: ------------ I think, there's a problem with type casting -- to be more specific, with boolean casting. When I was trying to print result of the condition (should be true, or false) I received some unexpected output. Reproduce code: --------------- <?php $b = 2; echo 'Should be false: ' . (!$b); echo '<br />'; echo (string) !$b; echo '<br />'; echo (bool) !$b; echo '<br />'; echo (int) !$b; echo '<br />'; echo 'Should be true: ' . ((bool) $b); echo '<br />'; var_dump(!$b); ?> Expected result: ---------------- Should be false: false false // or 0? false 0 Should be true: true bool(false) Actual result: -------------- Should be false: 0 Should be true: 1 bool(false) PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 10:00:02 2025 UTC |
You need to be able to get consistent behavior regardless of the cast, not everyone is just printing the output. $false = false; if ((string)$false)) { die("oops"); } If the typecast made it return "false" then you'd see the oops here.Hi again, > $false = false; > if ((string)$false)) { die("oops"); } > If the typecast made it return "false" > then you'd see the oops here. You gave too abstract example. Personally I haven't seen such construction. Most people, IMO, would rather do: $string = ''; if( !((bool) $string) ) { die("oops"); } Besides, I think, it's against the programming convention :) > You need to be able to get consistent > behavior regardless of the cast Well... doing (string)((int)((string) '153 foo')); you won't get '153 foo' as the result. So where's the "consistent behavior"? ;))