php php中定义的空变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9760753/
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
Empty variable define in php
提问by ZeroSuf3r
Before doing something with $error:
在用$error做一些事情之前:
$error = NULL;
In some script's saw:
在一些脚本中看到:
$error = '';
$error = false;
$error = 0;
- Which method is 'better' or maybe it depends in which situation i use it ?
- What's your suggestion ?
- 哪种方法“更好”,或者可能取决于我在哪种情况下使用它?
- 你有什么建议?
回答by Madara's Ghost
Depends on your design:
取决于您的设计:
- Are you setting it as an Object in case of error? Use
NULL
. - Are you setting it to
true
in case of error? Usefalse
. - Are you setting it as a number of some sort in case of error? Use
0
. - Are you setting it to a string to describe the error? Use
''
.
- 您是否将其设置为 Object 以防出错?使用
NULL
. - 您是否将其设置为
true
以防出错?使用false
. - 如果出现错误,您是否将其设置为某种数字?使用
0
. - 您是否将其设置为字符串来描述错误?使用
''
.
A better way to indicate errors would be throwing Exceptionsthough, rather than setting a variable and determine the error according to it.
一个更好的指示错误的方法是抛出异常,而不是设置一个变量并根据它确定错误。
回答by Loading
1.
1.
$v = NULL;
settype($v, 'string');
settype($v, 'int');
settype($v, 'float');
settype($v, 'bool');
settype($v, 'array');
var_dump($v);
2.
2.
$v = NULL;
var_dump( (string) $v);
var_dump( (int) $v);
var_dump( (float) $v);
var_dump( (bool) $v);
var_dump( (array) $v);
回答by Interrobang
There is no canonical answer to this question. As long as you use one of these semaphores consistently, you can use anything you want. Because PHP is loosely-typed, all of these values are "falsy" and can be evaluated in a boolean comparison as FALSE
.
这个问题没有规范的答案。只要您始终如一地使用这些信号量之一,您就可以使用任何您想要的东西。因为 PHP 是松散类型的,所以所有这些值都是“假的”并且可以在布尔比较中评估为FALSE
.
That said, there is more of a difference between the empty string and the others, so I'd stick with NULL
s and FALSE
s in this sort of scenario.
也就是说,空字符串和其他字符串之间存在更多差异,因此在这种情况下我会坚持使用NULL
s 和FALSE
s 。
回答by hjpotter92
It depends upon the conditions where you need to use the $error
. Using a NULL
is what I chose mostly as I deal more with MySQL clauses and all!
这取决于您需要使用$error
. 使用 aNULL
是我主要选择的,因为我更多地处理 MySQL 子句等等!