简体   繁体   中英

Why interpreter show undefined as NULL?

Last time I'm exploring PHP pretty much and I was curious if it's possible to define variable without initializing it like in C++.

Well interpreter doesn't output an fatal eror (only a notice that variable test is undefined) if I'll run this code:

<?php 

$test = (int) $test;

?>

And if I try to check it with var_dump() function i get:

int(0)

I assumed interpreter automatically cast undefined to integer. Well, ok it's pretty clever. But when I removed code repsonsible for type casting and checked it with var_dump() function I get:

NULL

Well, ok. So when I assign undefined variable as undefined variable I get variable with NULL. I can understand interpreter do it for me on the run. But when I try something like this:

<?php

var_dump($test);
var_dump($test);

?>

I get two notices that test is not defined, but var_dump() returns NULL, not undefined. And now I don't get it. If I'll turn off notices var_dump() function will have same result with undefined variables and variables assigned to NULL. And here comes a question from topic. Why interpreter (or rather a var_dump() function) treats undefined and NULL as same ?

The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.

A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet .
it has been unset().

(int)$test = casting, force a value to data type (integer)

warning notices = cause by $test is never defined, and you trying to use it

var_dump($test) = I dun have a value for $test, so, I return you a null (by PHP)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM