Created
May 31, 2021 09:32
-
-
Save kobus1998/cba019a7ee078e5dadd0b774b3fc44bf to your computer and use it in GitHub Desktop.
make a switch type check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class StrictSwitch | |
{ | |
private $val; | |
private $done = false; | |
public function __construct($val) | |
{ | |
$this->val = $val; | |
} | |
public function case($a, $c) | |
{ | |
if (!$this->done && $this->val === $a) { | |
$this->done = true; | |
$c(); | |
} | |
return $this; | |
} | |
public function default($c) | |
{ | |
if (!$this->done) { | |
$this->done = true; | |
$c(); | |
} | |
return $this; | |
} | |
} | |
$a = [ | |
'a', | |
'b' | |
]; | |
foreach ($a as $s) { | |
(new StrictSwitch(true)) | |
->case(strpos($s, 'a') !== false, function () use ($s) { | |
echo "a {$s}\n"; | |
}) | |
->case(strpos($s, 'b') !== false, function () use ($s) { | |
echo "b {$s}\n"; | |
}) | |
->default(function () { | |
echo "c\n"; | |
}); | |
} | |
// c | |
// c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment