Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created May 31, 2021 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/cba019a7ee078e5dadd0b774b3fc44bf to your computer and use it in GitHub Desktop.
Save kobus1998/cba019a7ee078e5dadd0b774b3fc44bf to your computer and use it in GitHub Desktop.
make a switch type check
<?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