【问题标题】:PHP Two Exclaimation Mark "!!" Operator with preg_match? [duplicate]PHP 两个感叹号“!!”带有 preg_match 的运算符? [复制]
【发布时间】:2013-02-19 13:50:13
【问题描述】:

在一个 PHP sn-p here 网上看到了这个。

/**
 * @param string $str subject of test for integerness
 * @return bool true if argument is an integer string
 */
function intStr($str) {
    return !!preg_match('/^\d+$/', $str);
}

运行这段代码 sn-p 产生:

> var_dump( intStr("abc") );
bool(false)

> var_dump( intStr("123") );
bool(true)

问题:

  1. 双感叹号是一个有效的操作符,还是和“not-not”一样,它自己否定?

  2. 还有,为什么这个运算符要与preg_match函数结合使用?

【问题讨论】:

  • cmets 说明一切:@return bool true [...]

标签: php operators


【解决方案1】:

preg_match 返回 0 或 1(或错误时为 false),此 intStr 函数旨在返回一个布尔值。单个!$x 首先将$x 转换为布尔值,然后取反。 !!$x 只是还原了这个否定,所以它是写(bool)$x 的更短的方式。

但是,这四个字符的保存会导致可读性下降(以及两个不必要的操作,但可以忽略不计),因此不建议这样做。

这是聪明的代码,但编程中有一条规则:Don't be clever

【讨论】:

    【解决方案2】:

    !! 等于 not not。这意味着!!'a' 会将字符串'a' 转换为布尔值,并返回它的倒数。所以,!!preg_match 表示 not not preg_match,所以是一个有效的 preg_match。

    【讨论】:

      【解决方案3】:

      运行这个简化的函数:

      function test($value) {
          return !!$value;
      }
      

      测试:

      > var_dump( test(1) );
      bool(true)
      
      > var_dump( test(0) );
      bool(false)
      
      > var_dump( test('1') );
      bool(true)
      
      > var_dump( test('0') );
      bool(false)
      
      > var_dump( is_bool( test('abc') ) );
      bool(true)
      
      > var_dump( is_bool( test('0') ) );
      bool(true)
      

      观察:

      使用is_bool 检查输出。 显然它以某种方式将输出强制转换为 boolean

      结论:

      来自 PHP 手册,

      preg_match() 如果模式匹配给定主题,则返回 1,如果不匹配,则返回 0,如果发生错误,则返回 FALSE。

      我可以得出结论,这个函数强制返回值为布尔值,而不是preg_match返回的整数值。

      【讨论】:

      • 实际上是一个布尔值
      猜你喜欢
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 2012-03-06
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      相关资源
      最近更新 更多