【问题标题】:How to find "if not null" using switch statement如何使用 switch 语句查找“if not null”
【发布时间】:2017-06-19 02:44:55
【问题描述】:

我有以下 switch 语句。我想知道如何制作“如果不为空”的案例。我很确定这是有效的,但我在 interwebz 上没有找到任何关于它的信息。

// Switch on Count
switch($this->_count) {
    case !"":
        return true;
    break;
    default: 
        return false;
    break;
}

所以写case !"":表示$this->_count不为null时返回true,否则返回false。我不能用那些看起来很奇怪的 if 语句来做到这一点吗?写有“?”的那个和一个“:”?我没用过那么多。任何帮助表示赞赏。谢谢!

【问题讨论】:

  • 我认为你只需要做return !empty($this->_count);
  • “我不能用那些看起来很奇怪的 if 语句来做这件事吗?用“?”和“:”写的那个?” - 仅供参考:这是称为三元运算符php.net/manual/en/language.operators.comparison.php

标签: php if-statement switch-statement


【解决方案1】:

不要试图过度设计这些东西,只需使用简单的 IF 语句:

if(is_null($this->_count)) {
    return false;
} else {
    return true;
}

或者超级简单:

return !is_null($this->_count);

不过,仅供参考,您可以使用 switch 来评估如下表达式:

switch(true) {
    case is_null($this->_count):
        return true; //dont need break; since return ends execution
    default:
        return false;
}

【讨论】:

  • 使用案例case !"": 是否也有效?还是使用 is_null() 函数更好?
  • 好吧 "" 是一个空字符串,我看不出它对测试有什么帮助是 null ......并且 !"" 在 PHP 中评估为 true(出于各种原因)。基本上,您当前拥有的caseif($this->_count === true),这绝不是在测试某些内容是否为空。
  • 感谢您的帮助!我会把你的答案标记为正确的! :P 我只是超级累,显然没有思考。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多