在PHP中初始化空字符串的正确方法是什么?

时间:2012-01-27 17:15:39

标签: php string initialization

在C#中,我采用以下初始化空字符串的方法:

string account = string.empty;

而不是

string account = "";

根据我的导师和其他C#开发人员的说法,第一种方法是更好的做法。

那就是说,有没有更好的方法在PHP中初始化空字符串?目前,我看到以下广泛使用:

$account = '';

感谢。

4 个答案:

答案 0 :(得分:27)

你所做的是正确的。没什么可说的。

示例:

$account = '';

if ($condition)  $account .= 'Some text';

echo  $account;

你可能会变得愚蠢并做这样的事情:

$str = (string) NULL;

..但这完全没有意义,而且它是完全相同的 - 一个空字符串。

你做对了。

答案 1 :(得分:5)

在大多数情况下,这是无关紧要的。与许多语言不同,在PHP中(通常)是否初始化变量并不重要。 PHP将自动转换未初始化(甚至未声明)的变量,以便立即使用。例如,以下都是正确的:

$a;
$a + 7; // Evaluates to 7
$a . "This is a test."; // Evaluates to "This is a test."
if (! $a) {}  // Evaluates as true

需要注意的是,select函数检查变量类型(严格等式检查,===)。例如,以下操作失败:

$a;
if (is_string($a)) {
    print 'success';
}
else {
    print 'fail';
}

但这种便利性成本很高。与严格键入(或者至少是“更严格”类型)的语言不同,核心语言本身没有任何东西可以帮助您捕获常见的程序员错误。例如,以下内容将很乐意执行,但可能与预期不符:

$isLoggedIn = getLoginStatus($user);
if ($isLogedIn) {
    // Will never run
    showOrder($user);
}
else {
    showLoginForm();
}

如果您选择初始化所有变量,请按照您的方式进行。但随后启用PHP通知(E_NOTICE)以获取有关未初始化变量的运行时警告。如果你不这样做,你基本上就是在浪费时间和按键来初始化你自己的变量。

答案 2 :(得分:3)

在PHP中处理字符串时,需要考虑以下其他一些事项:

// Localize based of possible existence
$account = (array_key_exists('account', $results)) ? $results['account'] : null;

// Check to see if string was actually initialized
return (isset($account)) ? $account : null

// If a function is passed an arg which is REQUIRED then validate it
if (empty($arg1)) {
    throw new Exception('Invalid $arg1');
}

echo $arg;

// If you are looking to append to string, then initialize it as you described
$account = null;

if (!empty($firstName)) {
    $account .= $firstName;
}

echo $account;

// Also, it's better to initialize as null, so you an do simple check constructs
if (is_null($account)) {
    // Do something
}

// Versus these types of checks
if ($account == '') {
    // Do something
} 

通常我会尽量避免像这样初始化vars。相反,我会在整个代码中进行本地化或检查是否存在,否则您最终会维护一个变量清单,这些变量可能实际上并不反映初始化后代码中的使用情况。

答案 3 :(得分:0)

chr(32)表示ASCII空间(即1字节长度的字符串)。

如果您想避免$myEmpty = " "$myEmpty = " "$myEmpty = ""之间的错误

有时很难分辨人眼何时有两个空格或一个或没有空格。使用已确定的chr函数。

对于真正空的字符串(零字节),没有其他办法,只需用$nothing = '';

等单引号定义它