【问题标题】:what does ($variable) return?($variable) 返回什么?
【发布时间】:2014-01-24 18:52:51
【问题描述】:

只是做一些验证,想真正了解这意味着什么,而不是仅仅工作。

假设我有:

$email = $_POST['email'];
if(!$email) { 
echo 'email empty'
}

什么只是有变量而没有检查它=什么意思?

我想

$variable

它本身意味着它将该变量返回为真。

所以我也在用 if

!$variable

is 表示假。

只是想弄清楚仅使用变量本身的实际含义。

比较变量是否为空也是不好的做法吗?

那么是不是更好用

$email == ''

!$email

对不起,如果这是一个没有真正答案的小问题需要解决,就像 100% 了解我正在编码的实际工作原理一样。

【问题讨论】:

  • 表达式中使用的任何变量都被评估为虚假或真实。 falsy 表示为空、null、等于 0 或为 false。真实是别的。所以,测试 !$var 测试你认为是假的所有类型的值。

标签: php variables definition


【解决方案1】:

PHP 使用http://www.php.net/manual/en/language.types.boolean.php 中定义的规则评估$email 是否“真实”。

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

PS $email= '' 会将'' 分配给$email

【讨论】:

    【解决方案2】:

    $email = '' 将清空变量。您可以改用=====

    在这种情况下,最好使用 PHP 的 isset() 函数(documentation)。该函数正在测试是否设置了变量而不是NULL

    【讨论】:

      【解决方案3】:

      当您执行if(<expression>) 时,它会计算<expression>,然后将其转换为布尔值。

      docs 中,它说:

      When converting to boolean, the following values are considered FALSE:
      
      the boolean FALSE itself
      the integer 0 (zero)
      the float 0.0 (zero)
      the empty string, and the string "0"
      an array with zero elements
      an object with zero member variables (PHP 4 only)
      the special type NULL (including unset variables)
      SimpleXML objects created from empty tags
      
      Every other value is considered TRUE (including any resource).
      

      因此,当您执行if(!$email) 时,它会按照上述规则将$email 转换为布尔值,然后反转该布尔值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 2017-04-12
        • 2019-12-04
        • 1970-01-01
        • 2014-04-30
        • 2021-10-11
        相关资源
        最近更新 更多