PHP代码替换问题是什么意思“”

时间:2018-08-30 17:58:39

标签: php

我无法理解$type = ''部分; 问题是: $type = '';是什么意思?尤其是撇号, 这是写出变量类型的函数。

     <?php

     function what_type($variable)
     {
     $type = '';
     if (is_integer($variable)) $type .= 'integer, '; else
     if (is_float($variable)) $type .= 'float, '; else
     if (is_string($variable)) $type .= 'string, ';
     if (is_numeric($variable)) 
     $type .= "and is_numeric($variable) === true";
     echo $type.'<br />'; 
     }

     $a = 7;
     $b = 3.25;
     $c = 'some code';
     $d = '55';

    echo '$a the value of 7 is the type of '; what_type($a);
    echo '$b the value of 3.25 is the type of '; what_type($b);
    echo '$c the value of ' . "'some code'" . ' is the type of ';
    what_type($c);                                            
    echo '$d the value of ' . "'55'" . ' is the type of '; what_type($d);
    ?>

2 个答案:

答案 0 :(得分:2)

$type = '';

这只是将变量$type初始化为空字符串。由于PHP默认将未声明的变量设置为空值,因此不需要明确指定此值。但是,如果您不初始化变量,然后再尝试更改它:

$type = $type . 'integer, ';

或使用它:

echo $type;

然后,您将从PHP收到警告,您正在尝试更改不存在的变量。因此,将变量设置为空的空白字符串是避免该警告的常见方法。

答案 1 :(得分:0)

此处$type = ''$type变量的默认值。 在您的示例中

if (is_integer($variable)) $type .= 'integer, '; else
if (is_float($variable)) $type .= 'float, '; else
if (is_string($variable)) $type .= 'string, ';
if (is_numeric($variable)) 
$type .= "oraz is_numeric($variable) === true";

仅当四个$type中的至少一个为true时,才设置if变量。 例如,如果$variable是布尔类型,则不会设置$type变量并得到未定义的变量错误,这就是为什么您需要为变量设置一些默认值以确保该变量肯定存在的原因。 / p>

相关问题