My assumption followed by question based on the assumption:
Javascript has null and undefined. You can set a variable to be null, implying it has no value, or you can set it to undefined, implying that it isn't known whether it has a value or not - it's just not set at all.
PHP has null, which so far I've used in the same way I'd use null in Javascript. Does PHP have an equivalent of undefined?
Not really, undefined has no counterpart in PHP. Comparing JS's undefined to PHP
s null doesn't really stack up, but it's as close as you're going to get. In both languages you can assign these values/non-values:
var nothingness = undefined;
$nothing = null;
and, if you declare a variable, but don't assign it anything, it would appear that JS resolves the var to undefined, and PHP resolves (or assigns) that variable null:
var nothingness;
console.log(nothingness === undefined);//true
$foo;
echo is_null($foo) ? 'is null' : '?';//is null
Be careful with isset, though:
$foo = null;
//clearly, foo is set:
if (isset($foo))
{//will never echo
echo 'foo is set';
}
The only real way to know if the variable exists, AFAIK, is by using get_defined_vars:
$foo;
$bar = null;
$defined = get_defined_vars();
if (array_key_exists($defined, 'foo'))
{
echo '$foo was defined, and assigned: '.$foo;
}
I don't think there is undefined. Rather than checking if something is undefined as you would in JavaScript:
if(object.property === undefined) // Doesn't exist.
You just use isset():
if(!isset($something)) // Doesn't exist.
Also, I think your understanding of undefined is a little odd. You shouldn't be setting properties to undefined, that's illogical. You just want to check if something is undefined, which means you haven't defined it anywhere within scope. isset() follows this concept.
That said, you can use unset() which I guess would be considered the same as setting something to undefined.
No. It only has "unset", which is not actually a value at all.
undefined is the value you'll get in Javascript when trying to access a property/variable which does not exist. You don't typically set something to undefined.
PHP does not have this mechanism. If you're trying to access a property or variable which does not exist, you will trigger an error of the level E_NOTICE. The script will continue, but the value of the non-existent variable will be substituted by null.
In Javascript you try to access a variable and test whether it you get undefined or not.
In PHP, you use isset($var) to test whether a variable exists before accessing it.
There are some scenarios where the null is a valid value, and there needs to be some other data type to signify the result of an action.
For example, I have a function to get the value of some key in a complex/nested array. The key value can be anything (including null). What should I return in this case if the key path is not valid? Returning null, false, -1, etc. wouldn't make any sense because the key value might be one of these.
What I decided to is define a constant:
define("undefined", "__undefined__");
...
$value = getKeyValue($options, ["section", "subsection", "opt2"]);
if ($value != undefined) {
...
}
Related
I was expecting to see a notice like PHP Notice: Undefined variable: a, however when I run this code it works perfectly fine. Moreover, the variable becomes NULL. Why?
<?php
function($a = 1) use (&$a) {};
var_dump($a); // NULL <---- Expected a Notice "undefined", got "NULL"
Demo
i think the & operator silently create the variable if it doesn't exist already. seems this page try to explain it:
If you assign, pass, or return an undefined variable by reference, it will get created. , so when you do use (&$a) , & sees that $a doesn't already exist, and create it..
as for undefined, that's not a real type in PHP. (unlike, for example, javascript, which actually have a type called undefined, and a separate type called null)
why null? given that undefined doesn't exist, its the only logical choice for the initial value, what did you expect it to be initialized to?
"If you don't initialize your variables with a default value, the PHP will do a type cast depending on how you are using the variable. This sometimes will lead to unexpected behaviour."
In maintaining code, I'm encountering loops, where at the end of the loop several variables are set to NULL like so: $var = NULL;. From what I understand in the manual, NULL is meant mostly as something to compare against in PHP code. Since NULL has no type and is not a string or number, outputting it makes no sense.
I unfortunately cannot provide an example, but I think the NULL values are being written to a file in our code. My question is: does $var have a value after the assignment, and will echoing/writing it produce output?
EDIT: I have read the PHP manual entry on NULL. There is no need to post this: http://php.net/manual/en/language.types.null.php in a comment or answer, or top downvote me for not having RTM. Thank you!
[ghoti#pc ~]$ php -r '$i="foo"; print "ONE\n"; var_dump($i); unset($i); print "TWO\n"; var_dump($i); $i=NULL; print "THREE\n"; var_dump($i); print "\n"; if (isset($i)) print "Set.\n"; if (is_null($i)) print "is_null\n";'
ONE
string(3) "foo"
TWO
NULL
THREE
NULL
is_null
[ghoti#pc ~]$
The result of isset() will be boolean false, but the variable is still defined. The isset() function would be better named isnotnull(). :-P
Note that is_null() will also return true for a value that has never been set.
Yay PHP.
null is pretty much just like any other value in PHP (actually, it's also a different data type than string, int, etc.).
However, there is one important difference: isset($var) checks for the var to exist and have a non-null value.
If you plan to read the variable ever again before assigning a new value, unset() is the wrong way to do but assigning null is perfectly fine:
php > $a = null;
php > if($a) echo 'x';
php > unset($a);
php > if($a) echo 'x';
Notice: Undefined variable: a in php shell code on line 1
php >
As you can see, unset() actually deletes the variable, just like it never existed, while assigning null sets it to a specific value (and creates the variable if necessary).
A useful use-case of null is in default arguments when you want to know if it was provided or not and empty strings, zero, etc. are valid, too:
function foo($bar = null) {
if($bar === null) { ... }
}
Null in PHP means a variable were no value was assigned.
http://php.net/manual/en/language.types.null.php
A variable could be set to NULL to indicate that it does not contain a value. It makes sense if at some later point in the code the variable is checked for being NULL.
A variable might be explicitly set to NULL to release memory used by it. This makes sense if the variable consumes lots of memory (see this question).
Dry run the code and you might be able to figure out the exact reason.
It appears that the purpose of the null implementation based off of the information provide is to clear the variable.
You can unset a variable in PHP by setting it to NULL or using the function unset().
unset() destroys the specified variables.
The behavior of unset() inside of a function can vary depending on
what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the
local variable is destroyed. The variable in the calling environment
will retain the same value as before unset() was called.
Null is a special data type which can have only one value, which is itself. Which is to say null is not only a data type but also a keyword literal a variable of data type null is a variable that has no value assigned to it when a variable is created without a value it is automatically assigned a value of null this is so that whatever garbage was in that memory location before is cleared out otherwise the program may try to process it
What is the correct way to write code that calls a function that accepts a variable pointer and changes the value?
The following works, but my IDE complains that $v is an undefined variable, which it is until the function it calls sets a value:
function foo(&$bar) {
$bar = 12345;
}
foo($v);
Should I initialize $v first to satisfy my IDE? Or is there a better way to do this?
$v = NULL;
foo($v);
When passing a variable by reference to a function, you need to have a reference to the variable from the calling code. To have a reference, the variable needs to exist. To exist, the variable needs to be initialized.
I recommend setting it to a reasonable default value. If the reasonable default is null, then use null. In some cases it may be more reasonable to use '' or 0 depending on what type of value you want the variable to hold.
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)
Here is my code:
<?php
$ja = '';
if(isset($ja))
echo "cool!";
?>
I get a "cool!" when running this simple piece of code in my browser. I learned from php.net that
isset — Determine if a variable is set
and is not NULL
Well, in my code, I did declare the variable $ja, but I didn't add any value to it, so shouldn't it be "NULL"?
Even though '' seems like nothing, it still has a value (a NULL character at the end of the string).
isset() checks if the variable is set or not, which in the case (to ''), it is. You may want to set $ja to NULL first beforehand, instead of setting it to an empty string... or use empty() ;)
The empty string is still a value. so you did give it a value which is not null - '' is a perfectly normal string value. perhaps you want ! empty($ja)
Isset is used to tell whether a variable is set or not:
isset($notDefined) //false
$notDefined = 0;
isset($notDefined) //true
(Assuming that $notDefined hasn't been defined before)
To check whether the variable is empty you can use if(empty($var)) or if($var==0)
You did add value to $ja - you set it to an empty string. An empty string is not null.
What you may be confused with is that an empty string and null both evaluate to "false" in PHP when you cast it to Boolean.
PHP's documentation is fairly clear on usage of isset.
The isset function does determine whether or not an object has a value. "NULL" is truly the only way to give an object a value of nothing. $s = '' simply gives an output of nothing. BOOL values(true/false) says that it's yes or no... 0 simply gives the object a int value of 0.
As the name implies of the function, it checks if some variable has been set, in a sense not that it has some value, but in a sense that it has been created. I think the name could be a bit confusing so I will bring a javascript analogy. In javascript to check if the variable exists you do the following:
if (typeof(somevar) == "undefined")
alert("Sorry, the variable has not been set already")
else
alert("Congratulations, the variable has not been set")
So, what you are doing is that you are making a variable $ja, and since by doing so, the variable already exists and therefore has been set.
Hope this helps