note 86049 deleted from control-structures.switch by crell

From: Date: Mon, 27 Jun 2022 20:37:43 +0000
Subject: note 86049 deleted from control-structures.switch by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218632@lists.php.net to get a copy of this message
Note Submitter: cretz ---- Haven't seen it mentioned here, but at least in my version (PHP 5.2.5) and I'm sure all of PHP 5, the switch statement is a great way to check type safe enumerates that are otherwise missing in the PHP language. Example: <?php class WannabeEnum { /** * @var WannabeEnum */ public static $FOO; /** * @var WannabeEnum */ public static $BAR; /** * @var WannabeEnum */ public static $FOOBAR; private $_ordinal; public function __construct($ordinal) { $this->_ordinal = $ordinal; } } WannabeEnum::$FOO = new WannabeEnum(1); WannabeEnum::$BAR = new WannabeEnum(2); WannabeEnum::$FOOBAR = new WannabeEnum(3); function testSwitch(WannabeEnum $wannabeEnum) { switch($wannabeEnum) { case WannabeEnum::$FOO: echo('Foo!' . PHP_EOL); break; case WannabeEnum::$BAR: echo('Bar!' . PHP_EOL); break; default: echo('Default!' . PHP_EOL); } } testSwitch(WannabeEnum::$FOO); testSwitch(WannabeEnum::$FOOBAR); ?> Outputs: Foo! Default! Don't forget it uses loose comparisons!

« previous php.notes (#218632) next »