어설 션과 같은 클래스를 만들고 원하는 로직을 넣으십시오. "true"메서드가 반환되는 한 $this(그리고 거짓 긍정을 피하기위한 다른 것은 없습니다.)
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;
}
또는 스위치를 실제 클래스에 넣을 수 있습니다.
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'));
물론 그 지점에서 확인중인 작업으로 수행하려는 작업을 재평가하고 대신 실제 유효성 검사 라이브러리를 사용하는 것이 좋습니다.