PHP에서 Null vs. False vs. 0
나는 좋은 개발자 / 자리 사이의 차이를 활용할 수 있다는 이야기입니다 Null
및 False
및 0
다른 모든 좋은 "아무것도"엔티티. PHP의 차이점 은
무엇입니까 ? 그것과 관련이 있습니까?===
언어에 따라 다르지만 PHP에서는 다음과 같습니다.
Null
" 아무것도 "를 의미합니다 . var이 초기화되지 않았습니다.
False
" 부울 컨텍스트에서 참이 아님 "을 의미 합니다 . 논리적 문제를 다루고 있음을 명시 적으로 보여주는 데 사용됩니다.
0
입니다 int
. 위의 나머지 부분과는 아무런 관련이 없으며 수학에 사용됩니다.
이제 까다로운 점은 PHP와 같은 동적 언어에서 모두 부울 컨텍스트 (PHP) 의 값을 갖는 것 입니다 False
.
로 ==
테스트하면 부울 값을 테스트하므로 평등을 얻습니다. 로 ===
테스트하면 유형이 테스트되고 불평등이 발생합니다.
그렇다면 왜 유용합니까?
글쎄, strrpos()
기능을 보라 . 아무것도 찾지 못하면 False를 반환하지만 문자열의 시작 부분에서 무언가를 발견하면 0을 반환합니다!
<?php
// pitfall :
if (strrpos("Hello World", "Hello")) {
// never exectuted
}
// smart move :
if (strrpos("Hello World", "Hello") !== False) {
// that works !
}
?>
그리고 물론, 당신이 상태를 다루는 경우 :
DebugMode = False
(꺼짐으로 설정), DebugMode = True
(켜짐으로 설정) 및 DebugMode = Null
(절대로 설정하지 않으면 하드 디버깅이 발생합니다 ;-)) 의 차이를 만들고 싶습니다 .
null
입니다 null
. false
입니다 false
. 슬프지만 사실이야.
PHP에는 일관성이별로 없습니다. 개발자 가 널 (null)을 작성 하려고 하면 "비 소유"또는 "존재하지 않음"을 의미합니다. 그러나 종종 False는 '존재하지 않는'역할을합니다 (예 : strrpos ( 'fail', 'search')는 null이 아닌 false를 반환 함)
그들은 이미 무언가에 대해 거짓을 사용하고있을 때 종종 null이 사용되는 것을 볼 수 있습니다. 예 : filter_input (). 변수가 필터에 실패하면 false를 리턴합니다. 변수가 존재하지 않으면 null (존재하지 않음은 필터도 실패했음을 의미하므로 왜 null을 반환합니까?!?)
PHP는 함수에서 데이터를 반환하는 편리함이 있습니다. 그리고 개발자는 데이터 대신 모든 종류의 장애 상태에 빠지게됩니다.
그리고 PHP에서 실패 (false, null)에서 데이터 (int, str 등)를 감지하는 확실한 방법은 없습니다.
함수에 따라 항상 === null 또는 === false를 테스트해야합니다. 또는 filter_input () / filter_var ()와 같은 경우
그리고 저글링 유형에 재미가 있습니다. 배열과 객체도 포함하지 않습니다.
var_dump( 0<0 ); #bool(false)
var_dump( 1<0 ); #bool(false)
var_dump( -1<0 ); #bool(true)
var_dump( false<0 ); #bool(false)
var_dump( null<0 ); #bool(false)
var_dump( ''<0 ); #bool(false)
var_dump( 'a'<0 ); #bool(false)
echo "\n";
var_dump( !0 ); #bool(true)
var_dump( !1 ); #bool(false)
var_dump( !-1 ); #bool(false)
var_dump( !false ); #bool(true)
var_dump( !null ); #bool(true)
var_dump( !'' ); #bool(true)
var_dump( !'a' ); #bool(false)
echo "\n";
var_dump( false == 0 ); #bool(true)
var_dump( false == 1 ); #bool(false)
var_dump( false == -1 ); #bool(false)
var_dump( false == false ); #bool(true)
var_dump( false == null ); #bool(true)
var_dump( false == '' ); #bool(true)
var_dump( false == 'a' ); #bool(false)
echo "\n";
var_dump( null == 0 ); #bool(true)
var_dump( null == 1 ); #bool(false)
var_dump( null == -1 ); #bool(false)
var_dump( null == false ); #bool(true)
var_dump( null == null ); #bool(true)
var_dump( null == '' ); #bool(true)
var_dump( null == 'a' ); #bool(false)
echo "\n";
$a=0; var_dump( empty($a) ); #bool(true)
$a=1; var_dump( empty($a) ); #bool(false)
$a=-1; var_dump( empty($a) ); #bool(false)
$a=false; var_dump( empty($a) ); #bool(true)
$a=null; var_dump( empty($a) ); #bool(true)
$a=''; var_dump( empty($a) ); #bool(true)
$a='a'; var_dump( empty($a)); # bool(false)
echo "\n"; #new block suggested by @thehpi
var_dump( null < -1 ); #bool(true)
var_dump( null < 0 ); #bool(false)
var_dump( null < 1 ); #bool(true)
var_dump( -1 > true ); #bool(false)
var_dump( 0 > true ); #bool(false)
var_dump( 1 > true ); #bool(true)
var_dump( -1 > false ); #bool(true)
var_dump( 0 > false ); #bool(false)
var_dump( 1 > true ); #bool(true)
아래는 예입니다.
Comparisons of $x with PHP functions
Expression gettype() empty() is_null() isset() boolean : if($x)
$x = ""; string TRUE FALSE TRUE FALSE
$x = null; NULL TRUE TRUE FALSE FALSE
var $x; NULL TRUE TRUE FALSE FALSE
$x is undefined NULL TRUE TRUE FALSE FALSE
$x = array(); array TRUE FALSE TRUE FALSE
$x = false; boolean TRUE FALSE TRUE FALSE
$x = true; boolean FALSE FALSE TRUE TRUE
$x = 1; integer FALSE FALSE TRUE TRUE
$x = 42; integer FALSE FALSE TRUE TRUE
$x = 0; integer TRUE FALSE TRUE FALSE
$x = -1; integer FALSE FALSE TRUE TRUE
$x = "1"; string FALSE FALSE TRUE TRUE
$x = "0"; string TRUE FALSE TRUE FALSE
$x = "-1"; string FALSE FALSE TRUE TRUE
$x = "php"; string FALSE FALSE TRUE TRUE
$x = "true"; string FALSE FALSE TRUE TRUE
$x = "false"; string FALSE FALSE TRUE TRUE
PHP에서 유형 비교 에 대한 자세한 내용은 이것을 참조하십시오 . 그것은 당신에게 명확한 이해를 제공해야합니다.
PHP에서는 === 및! == 연산자를 사용하여 값이 같은지 여부와 유형이 일치하는지 확인할 수 있습니다. 예를 들어, 그래서는 : 0 == false
이다 true
, 그러나 0 === false
입니다 false
. 동일은 간다 !=
대 !==
. 또한 null
언급 된 연산자를 사용하여 다른 두 개와 비교할 때 비슷한 결과를 기대하십시오.
PHP에서이 값의 품질은 보통 때로는 0
0 이 될 수있는 값을 반환 할 때 사용 되지만 때로는 함수가 실패했을 수도 있습니다. 이러한 경우 PHP로 돌아가서 false
identity 연산자를 사용하여 이러한 경우를 확인해야합니다 ===
. 예를 들어, 다른 문자열 내에서 한 문자열의 위치를 검색하고을 사용하는 strpos()
경우이 함수는 문자열이 맨 처음에 발견되면 문자열 위치를 찾지 못하면 0이 될 수있는 숫자 위치를 반환합니다. 모두 strpos()
반환 false
되면 결과를 처리 할 때이 점을 고려해야합니다.
함수에서 동일한 기술을 사용하면 표준 PHP 라이브러리에 익숙한 사람은 진행 상황과 반환 값이 원하는지 또는 처리하는 동안 오류가 발생했는지 확인하는 방법을 이해합니다. 실제로 함수 매개 변수도 마찬가지입니다. 배열 또는 문자열인지 여부에 따라 다르게 처리 할 수 있으며이 기술은 PHP 전체에서 많이 사용되므로 누구나 쉽게 얻을 수 있습니다. 그래서 나는 그것이 힘이라고 생각합니다.
False, Null, Nothing, 0, Undefined 등
이들 각각은 실제 개념과 관련이있는 특정 의미를 갖습니다. 때때로 여러 의미가 단일 키워드 또는 값으로 과부하됩니다.
In C and C++, NULL
, False
and 0
are overloaded to the same value. In C# they're 3 distinct concepts.
null
or NULL
usually indicates a lack of value, but usually doesn't specify why. 0
indicates the natural number zero and has type-equivalence to 1, 2, 3, etc. and in languages that support separate concepts of NULL
should be treated only a number.
False indicates non-truth. And it used in binary values. It doesn't mean unset, nor does it mean 0
. It simply indicates one of two binary values.
Nothing can indicate that the value is specifically set to be nothing which indicates the same thing as null, but with intent.
Undefined in some languages indicates that the value has yet to be set because no code has specified an actual value.
I have just wasted 1/2 a day trying to get either a 0
, null
, false
to return from strops
!
Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding:
Concept take a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done.
Anyway here was the basis of the cosing:
if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ())
{
do this
} else {
or that
}
{
echo strpos(mydomain.co.uk, mydomain);
if ( strpos(mydomain, xmas) == null )
{
echo "\n1 is null";
}
if ( (strpos(mydomain.co.uk, mydomain)) == 0 )
{
echo "\n2 is 0";
} else {
echo "\n2 Something is WRONG";
}
if ( (mydomain.co.uk, mydomain)) != 0 )
{
echo "\n3 is 0";
} else {
echo "\n3 it is not 0";
}
if ( (mydomain.co.uk, mydomain)) == null )
{
echo "\n4 is null";
} else {
echo "\n4 Something is WRONG";
}
}
FINALLY after reading this Topic, I found that this worked!!!
{
if ((mydomain.co.uk, mydomain)) !== false )
{
echo "\n5 is True";
} else {
echo "\n5 is False";
}
}
Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as false
, as its also can be a NULL
day!
After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as False
, NULL
and 0
are not all the same as True or False or NULL
?
From the PHP online documentation:
To explicitly convert a value to boolean, use the (bool) or (boolean) casts.
However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
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 consideredTRUE
(including any resource).
So, in most cases, it's the same.
On the other hand, the ===
and the ==
are not the same thing. Regularly, you just need the "equals" operator. To clarify:
$a == $b //Equal. TRUE if $a is equal to $b.
$a === $b //Identical. TRUE if $a is equal to $b, and they are of the same type.
For more information, check the "Comparison Operators" page in the PHP online docs.
Hope this helps.
The differences between these values always come down to detailed language-specific rules. What you learn for PHP isn't necessarily true for Python, or Perl, or C, etc. While it is valuable to learn the rules for the language(s) you're working with, relying on them too much is asking for trouble. The trouble comes when the next programmer needs to maintain your code and you've used some construct that takes advantage of some little detail of Null vs. False (for example). Your code should look correct (and conversely, wrong code should look wrong).
Null is used in databases to represent "no record" or "no information". So you might have a bit field that describes "does this user want to be sent e-mails by us", where True means they do, False means they don't want to be sent anything, but Null would mean that you don't know. They can come about through outer joins and suchlike.
The logical implications of Null are often different - in some languages NULL is not equal to anything, so if(a == NULL) will always be false.
So personally I'd always initialise a boolean to FALSE, and initialising one to NULL would look a bit icky (even in C where the two are both just 0... just a style thing).
I think bad developers find all different uses of null/0/false in there code.
For example, one of the most common mistakes developers make is to return error code in the form of data with a function.
// On error GetChar returns -1
int GetChar()
This is an example of a sugar interface. This is exsplained in the book "Debuging the software development proccess" and also in another book "writing correct code".
The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot.
Instead, the best way is not to mix error code with your data. So the following function.
char GetChar()
now becomes
// On success return 1
// on failure return 0
bool GetChar(int &char)
This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code.
So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine.
In PHP it depends on if you are validating types:
(
( false !== 0 ) && ( false !== -1 ) && ( false == 0 ) && ( false == -1 ) &&
( false !== null ) && ( false == null )
)
Technically null is 0x00
but in PHP ( null == 0x00 ) && ( null !== 0x00 )
.
0
is an integer value.
One interesting fact about NULL
in PHP: If you set a var equal to NULL
, it is the same as if you had called unset()
on it.
NULL
essentially means a variable has no value assigned to it; false
is a valid Boolean value, 0
is a valid integer value, and PHP has some fairly ugly conversions between 0
, "0"
, ""
, and false
.
Null is nothing, False is a bit, and 0 is (probably) 32 bits.
Not a PHP expert, but in some of the more modern languages those aren't interchangeable. I kind of miss having 0 and false be interchangeable, but with boolean being an actual type you can have methods and objects associated with it so that's just a tradeoff. Null is null though, the absence of anything essentially.
Well, I can't remember enough from my PHP days to answer the "===" part, but for most C-style languages, NULL should be used in the context of pointer values, false as a boolean, and zero as a numeric value such as an int. '\0' is the customary value for a character context. I usually also prefer to use 0.0 for floats and doubles.
So.. the quick answer is: context.
In pretty much all modern languages, null logically refers to pointers (or references) not having a value, or a variable that is not initialized. 0 is the integer value of zero, and false is the boolean value of, well, false. To make things complicated, in C, for example, null, 0, and false are all represented the exact same way. I don't know how it works in PHP.
Then, to complicate things more, databases have a concept of null, which means missing or not applicable, and most languages don't have a direct way to map a DBNull to their null. Until recently, for example, there was no distinction between an int being null and being zero, but that was changed with nullable ints.
Sorry to make this sound complicated. It's just that this has been a harry sticking point in languages for years, and up until recently, it hasn't had any clear resolution anywhere. People used to just kludge things together or make blank or 0 represent nulls in the database, which doesn't always work too well.
False and 0 are conceptually similar, i.e. they are isomorphic. 0 is the initial value for the algebra of natural numbers, and False is the initial value for the Boolean algebra.
In other words, 0 can be defined as the number which, when added to some natural number, yields that same number:
x + 0 = x
Similarly, False is a value such that a disjunction of it and any other value is that same value:
x || False = x
Null is conceptually something totally different. Depending on the language, there are different semantics for it, but none of them describe an "initial value" as False and 0 are. There is no algebra for Null. It pertains to variables, usually to denote that the variable has no specific value in the current context. In most languages, there are no operations defined on Null, and it's an error to use Null as an operand. In some languages, there is a special value called "bottom" rather than "null", which is a placeholder for the value of a computation that does not terminate.
I've written more extensively about the implications of NULL elsewhere.
Somebody can explain to me why 'NULL' is not just a string in a comparison instance?
$x = 0;
var_dump($x == 'NULL'); # TRUE !!!WTF!!!
The issues with falsyness comes from the PHP history. The problem targets the not well defined scalar type.
'*' == true -> true (string match)
'*' === true -> false (numberic match)
(int)'*' == true -> false
(string)'*' == true -> true
PHP7 strictness is a step forward, but maybe not enough. https://web-techno.net/typing-with-php-7-what-you-shouldnt-do/
참고URL : https://stackoverflow.com/questions/137487/null-vs-false-vs-0-in-php
'Programing' 카테고리의 다른 글
IEnumerable에서 첫 번째 요소를 얻는 방법 (0) | 2020.06.20 |
---|---|
mysql 클라이언트 (Linux) 만 설치하는 방법이 있습니까? (0) | 2020.06.20 |
HTML 사이트에 사용자 정의 글꼴을 설치하는 방법 (0) | 2020.06.20 |
왜 평가가 정확히 악한가? (0) | 2020.06.20 |
Ruby 콘솔에서 고안 사용자 생성 (0) | 2020.06.20 |