Erstellen Sie eine Assertions-ähnliche Klasse und fügen Sie die gewünschte Logik ein. solange "wahre" Methoden zurückkehren $this(und nichts anderes, um Fehlalarme zu vermeiden).
class Haystack
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
public function isExactly($n)
{
if ($n === $this->value)
return $this;
}
}
$var = new Haystack(null);
switch ($var) {
case $var->isExactly(''):
echo "the value is an empty string";
break;
case $var->isExactly(null):
echo "the value is null";
break;
}
Oder Sie können Ihren Schalter in die eigentliche Klasse stellen:
class Checker
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
public function isExactly($n)
{
if ($n === $this->value)
return $this;
}
public function contains($n)
{
if (strpos($this->value, $n) !== false)
return $this;
}
public static function check($str)
{
$var = new self($str);
switch ($var) {
case $var->isExactly(''):
return "'$str' is an empty string";
case $var->isExactly(null):
return "the value is null";
case $var->contains('hello'):
return "'$str' contains hello";
default:
return "'$str' did not meet any of your requirements.";
}
}
}
var_dump(Checker::check('hello world'));
Natürlich möchten Sie an diesem Punkt möglicherweise neu bewerten, was Sie mit dem, was Sie überprüfen, tun möchten, und stattdessen eine echte Validierungsbibliothek verwenden.