PHP两个惊叹号“!!”有preg_match的运算符?

时间:2013-03-05 08:32:58

标签: php operators

在一个PHP代码段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);
}

运行此代码段会产生:

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

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

问题:

  1. 双重感叹号是一个有效的运算符,还是与“not-not”相同,否定了它?

  2. ,为什么此运算符与preg_match函数一起使用?

3 个答案:

答案 0 :(得分:2)

preg_match返回0或1(错误时为false),此intStr函数用于返回布尔值。单!$x首先将$x转换为布尔值,然后否定。 !!$x只是恢复了这种否定,所以写(bool)$x是一种较短的方式。

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

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

答案 1 :(得分:0)

运行此简化功能:

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检查输出。 显然它以某种方式将输出强制/强制输出为布尔

<强>结论:

从PHP手册

  如果模式与给定主题匹配,则

preg_match()返回1,否则返回0;如果发生错误,则返回FALSE。

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

答案 2 :(得分:0)

!!等于not not。这意味着!!'a'会将字符串'a'强制转换为布尔值,并返回该值的反转。因此,!!preg_match表示not not preg_match,因此是有效的preg_match。