문제

나는 좋은 개발자를 발견 할 수 있/을 활용의 차이 NullFalse0 과 다른 모든 좋은""아무것도체.
What 의 차이점을 구체적으로,PHP?그것은 함께 할 수있는 뭔가 ===?

도움이 되었습니까?

해결책

언어에 따라 다르지만 php :

Null 수단 "아무것도 아님". VAR은 초기화되지 않았습니다.

False 수단 "부울 맥락에서는 사실이 아닙니다". 논리적 문제를 다루고 있음을 명시 적으로 보여주기 위해 사용되었습니다.

0 이다 int. 수학에 사용되는 위의 나머지 부분과 관련이 없습니다.

이제 까다로운 점은 PHP와 같은 역동적 인 언어로 그들 모두 부울 맥락에서 가치가 있습니다., 어느 (PHP)입니다 False.

당신이 그것을 테스트하면 ==, 부울 가치를 테스트하고 있으므로 평등을 얻게됩니다. 당신이 그것을 테스트하면 ===, 그것은 유형을 테스트하고 불평등을 얻게됩니다.

그렇다면 왜 유용합니까?

글쎄, strrpos() 기능. 아무것도 찾지 못하면 거짓을 반환하지만, 스트링의 시작 부분에서 무언가를 찾은 경우 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에는 일관성이 많지 않습니다. 개발자 노력하다 널을 만드는 것은 "무제한"또는 "존재하지 않는"것을 의미합니다. 그러나 종종 거짓은 '존재하지 않는'역할을합니다 (예 : strrpos ( 'fail', 'search')는 거짓을 반환하고 null이 아닙니다)

당신은 그들이 이미 무언가에 대해 false를 사용하고있을 때 null이 사용되는 것을 종종 볼 수 있습니다. EG Filter_Input (). 변수가 필터에 실패하면 False를 반환합니다. 그리고 변수가 존재하지 않으면 null (기존이 없다는 것은 필터에 실패한 것을 의미합니까? 그래서 왜 null을 반환 하는가?!?)

PHP는 함수에서 데이터를 반환하는 편의성을 가지고 있습니다. 그리고 개발자들은 데이터 대신 모든 종류의 실패 상태에서 cram을 cram합니다.

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 == falsetrue, 하지만, 0 === falsefalse.동 !=!==.또한 경우에는 비교할 null 다른 두 사용하여 언급자니다.

지금 PHP 이품질의 값은 일반적으로 사용되는 때에 값을 반환하는이 될 수 있습니다 때로는 0 (zero),하지만 때로는 그것이 될 수 있는 함수에 실패했습니다.이러한 경우에 PHP 아 false 을 확인에 대한 이러한 경우 id 를 사용하여 운영자 ===.예를 들어,당신은 위치에 한 문자열의 내부를 다른 사용 strpos(), 이 기능이 반환됩니다 숫자의 위치는 할 수 있습 0 문자열이 발견되면에서 시작하지만,경우에는 문자열을 발견되지 않는 모두에서,다음 strpos()false 당신이 계정으로 처리 할 때 결과입니다.

당신이 사용하는 것과 동일한 기술에서 당신의 기능에 익숙한 사람과 함께 표준 PHP 라이브러리를 이해하는 방법을 확인하는 경우에 반환되는 값은 무엇을 원하거나 어떤 오류 처리하는 동안 발생.동일한 실제로 기능을 위한 params 처리할 수 있습니다 그들을 다르게 경우에 따라 그들은 어레이 또는 문자열이나 무엇인지,그리고 이 기술은 사용되는 PHP 무겁게,그래서 모두가 그것을 얻을 것이 매우 쉽습니다.그래서 나는 힘이 있습니다.

거짓, 널, 아무것도, 0, 정의되지 않은, 등 등

이들 각각은 실제 개념과 관련이있는 특정한 의미를 갖습니다. 때로는 여러 의미가 단일 키워드 또는 값으로 과부하됩니다.

~ 안에 그리고 C ++, NULL, False 그리고 0 동일한 값으로 과부하됩니다. ~ 안에 씨# 그것들은 3 개의 뚜렷한 개념입니다.

null 또는 NULL 일반적으로 가치 부족을 나타내지 만 일반적으로 이유를 지정하지 않습니다.0 자연 숫자가 0을 나타내며 유형 동등성을 나타냅니다 1, 2, 3, 별도의 개념을 지원하는 언어 등 NULL 숫자 만 처리해야합니다.

거짓 비 진실을 나타냅니다. 그리고 그것은 사용되었습니다 이진 값. 그것은 설정을 의미하지도 않고 의미가 없습니다 0. 단순히 두 가지 이진 값 중 하나를 나타냅니다.

값이 구체적으로 널과 동일한 것을 나타내는 것은 아니지만 의도를 나타내는 것은 아무것도 없다는 것을 나타내는 것은 없습니다.

일부 언어로 정의되지 않은 것은 코드가 실제 값을 지정하지 않았기 때문에 값이 아직 설정되지 않았 음을 나타냅니다.

나는 하루에 1/2를 낭비했다. 0, null, false 돌아 오기 위해 strops!

논리가 올바른 방향으로 흐르지 않았다는 것을 알기 전에, PHP 코딩에 블랙 홀이있는 것처럼 보이기 전에 내가하려고했던 모든 것입니다.

개념은 서버에서 호스팅 된 도메인 이름을 사용하여 루트 레벨이 아닌지 확인하고,이를 수행하는 몇 가지 방법이 있지만, 내가 수행 한 다른 PHP 기능/ 구성으로 인해 다르게 선택했습니다.

어쨌든 여기에 포기의 기초가있었습니다.

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"; 
    }
}

마침내이 주제를 읽은 후, 나는 이것이 효과가 있음을 발견했습니다 !!!

{
if ((mydomain.co.uk, mydomain)) !== false ) 
    {
        echo "\n5 is True"; 
    } else {
        echo "\n5 is False"; 
    }
}

이 기사에 감사드립니다. 이제 크리스마스이지만 크리스마스가 아닐 수도 있습니다. false, 그것의 a NULL 낮!

간단한 코드를 디버깅하는 날을 낭비한 후, 나는 문제를 식별 할 수 있었기 때문에이 사실을 알게 되었기 때문에 이전에 문제를 식별 할 수 있었기 때문에 그것을 알고 있었기를 바랐습니다. 작동하지 않았습니다 False, NULL 그리고 0 모두 동일하지 않습니다 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 considered TRUE (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/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top