php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50878 switch on constant does not enter correct block
Submitted: 2010-01-29 08:29 UTC Modified: 2010-01-29 08:44 UTC
From: stephan dot schulze at kapthon dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3.1 OS: CentOs 5.4
Private report: No CVE-ID: None
 [2010-01-29 08:29 UTC] stephan dot schulze at kapthon dot com
Description:
------------
If a class function returns a class constant or true and the result is checked with a switch, the switch does not enter the correct block.
I expect $bResult should be converted to 1 if it is "true" but not to -1.

Reproduce code:
---------------
<?php
class Foo {
   const ERR_ONE = -1;
   
   public function bar() {
      return true;
   }
   
   public function isErr() {
      return self::ERR_ONE;
   }
}
$oFoo = new Foo();
$bResult = $oFoo->bar();
switch ($bResult) {
   case Foo::ERR_ONE:
      "ERR_ONE: " . var_dump($bResult);      
   break;  
   default:
      echo "default";
   break; 
}

$bResult = $oFoo->isErr();
switch ($bResult) {
   case Foo::ERR_ONE:
      "ERR_ONE: " . var_dump($bResult);      
   break;  
   default:
      echo "default";
   break;  
}

Expected result:
----------------
Expected to get
"default" and "ERR_ONE: int(-1)"

Actual result:
--------------
ERR_ONE: bool(true) ERR_ONE: int(-1) 

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-01-29 08:44 UTC] aharvey@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

Switch uses loose comparison, so using a boolean true as the expression to be switched by will match any non-zero case.

Case in point:

<?php
$f = true;
switch ($f) {
    case -1:
        echo "matched\n";
        break;

    default:
        echo "default\n";
}
?>

This prints "matched", since -1 == true. This is documented (in some detail) at http://au2.php.net/manual/en/types.comparisons.php#types.comparisions-loose
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 24 23:00:02 2025 UTC