note 86049 added to control-structures.switch

From: Date: Wed, 01 Oct 2008 00:56:51 +0000
Subject: note 86049 added to control-structures.switch
Groups: php.notes 
Request: Send a blank email to php-notes+get-144922@lists.php.net to get a copy of this message
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! ---- Server IP: 208.69.120.35 Probable Submitter: 76.184.68.162 ---- Manual Page -- http://www.php.net/manual/en/control-structures.switch.php Edit -- https://master.php.net/note/edit/86049 Del: integrated -- https://master.php.net/note/delete/86049/integrated Del: useless -- https://master.php.net/note/delete/86049/useless Del: bad code -- https://master.php.net/note/delete/86049/bad+code Del: spam -- https://master.php.net/note/delete/86049/spam Del: non-english -- https://master.php.net/note/delete/86049/non-english Del: in docs -- https://master.php.net/note/delete/86049/in+docs Del: other reasons-- https://master.php.net/note/delete/86049 Reject -- https://master.php.net/note/reject/86049 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#144922) next »