在 PHP 中初始化空字符串的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9037321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the proper way to initialize empty strings in PHP?
提问by kaspnord
In C#, I've come to adopt the following method of initializing empty strings:
在C#中,我开始采用以下初始化空字符串的方法:
string account = string.empty;
rather than
而不是
string account = "";
According to my mentor and other C# developers I've talked to, the first method is the better practice.
根据我的导师和我与之交谈过的其他 C# 开发人员的说法,第一种方法是更好的做法。
That said, is there a better way to initialize empty strings in PHP? Currently, I see the following widely used:
也就是说,有没有更好的方法在 PHP 中初始化空字符串?目前,我看到以下广泛使用:
$account = '';
Thanks.
谢谢。
回答by Wesley Murch
What you're doing is correct. Not much more to say about it.
你在做什么是正确的。关于它没有更多要说的。
Example:
例子:
$account = '';
if ($condition) $account .= 'Some text';
echo $account;
You could get silly and do something like this:
你可能会变得愚蠢并做这样的事情:
$str = (string) NULL;
..but that's utterly pointless, and it's exactly the same thing - an empty string.
..但那完全没有意义,而且完全一样 - 一个空字符串。
You're doing it right.
你做得对。
回答by Conrad Shultz
For the most part this is irrelevant. Unlike many languages, in PHP it (usually) doesn't matter whether you initialize a variable. PHP will automatically cast an uninitialized (or even undeclared) variable as appropriate for the immediate use. For example, the following are all correct:
在大多数情况下,这无关紧要。与许多语言不同,在 PHP 中,它(通常)是否初始化变量并不重要。PHP 将自动转换为适合立即使用的未初始化(甚至未声明)变量。例如,以下都是正确的:
$a;
$a + 7; // Evaluates to 7
$a . "This is a test."; // Evaluates to "This is a test."
if (! $a) {} // Evaluates as true
The one caveat is that select functions check for variable type (as does strict equality checking, ===). For example, the following fails:
一个警告是选择函数检查变量类型(严格相等检查,===)。例如,以下失败:
$a;
if (is_string($a)) {
print 'success';
}
else {
print 'fail';
}
This convenience comes at a heavy cost, though. Unlike strictly typed (or, at least, "more strictly" typed) languages, there is nothing in the core language itself to help you catch common programmer errors. For example, the following will happily execute, but probably not as expected:
但是,这种便利需要付出沉重的代价。与严格类型(或至少是“更严格”类型)语言不同,核心语言本身没有任何内容可以帮助您捕获常见的程序员错误。例如,以下将愉快地执行,但可能不会按预期执行:
$isLoggedIn = getLoginStatus($user);
if ($isLogedIn) {
// Will never run
showOrder($user);
}
else {
showLoginForm();
}
If you choose to initialize all your variables, do it just as you did. But then enable PHP notices (E_NOTICE) to get run-time warnings about uninitialized variables. If you don't, you're basically wasting time and keystrokes initializing your own variable.
如果您选择初始化所有变量,请按照您的方式进行。但随后启用 PHP 通知 (E_NOTICE) 以获取有关未初始化变量的运行时警告。如果你不这样做,你基本上是在浪费时间和按键初始化你自己的变量。
回答by Mike Purcell
Here are some other things to consider when working with strings in PHP:
以下是在 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
}
Normally I try to avoid initializing vars like this. Instead I localize, or check for existence throughout the code, otherwise you end up maintaining a laundry list of variables which may not actually reflect usage throughout the code following initialization.
通常我会尽量避免像这样初始化变量。相反,我会在整个代码中进行本地化或检查是否存在,否则您最终会维护一个变量清单,这些变量可能实际上无法反映初始化后整个代码的使用情况。
回答by stamster
chr(32)
represents ASCII space (i.e. string of 1 byte length).
chr(32)
表示 ASCII 空间(即 1 个字节长度的字符串)。
If you want to avoid mistakes like $myEmpty = " "
vs. $myEmpty = " "
vs. $myEmpty = ""
如果你想避免诸如$myEmpty = " "
vs. $myEmpty = " "
vs. 之类的错误。$myEmpty = ""
Sometimes it's hard to tell when there are two spaces or one or none by human eyes. Using chr
function that is solved for sure.
有时,人眼很难分辨什么时候有两个空格,一个或一个没有。使用chr
肯定解决的功能。
And for really empty string (zero bytes), there's no other way but to simply define it with (single) quotation marks like $nothing = '';
对于真正的空字符串(零字节),除了用(单)引号简单地定义它之外别无他法,例如 $nothing = '';