make switch use === comparison not == comparison In PHP

后端 未结 15 2199
一向
一向 2020-11-28 07:09

Is there anyway to make it so that the following code still uses a switch and returns b not a? Thanks!

$var = 0;
switch($var) {
            


        
15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 07:27

    Create an assertion-like class and put whatever logic you want in it; so long as "true" methods return $this (and nothing else to avoid false-positives.)

    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;
    }
    

    Or you can put your switch inside the actual class:

    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'));   # string(28) "'hello world' contains hello"
    

    Of course that that point you might want to re-evaluate what you want to do with what you're checking and use a real validation library instead.

提交回复
热议问题