It depends on what you mean by "set".
If you mean "I can use the variable in my code without generating undefined variable notices", then a variable is set when it has any value. You can't declare a variable in PHP without assigning it a value. For example:
<?php
$var;
Does not create the $var
variable. Trying to use that $var
for anything after that line of code will give you an undefined variable notice, and if you print_r(get_defined_vars());
you'll get an empty array.
If you mean "isset($var)
will return true
", then a variable is set when it has any value other than null
. For example:
<?php
$varX = null;
$varY = 0;
With these variables, both are defined. You can use them in your code without getting undefined variable notices. print_r(get_defined_vars());
will show you Array ( [varX] => [varY] => 0 )
. But isset($varX)
returns false
even though $varX
is defined, because it has a null
value.
Once you have assigned a value to a variable, it will remain defined within its scope unless you explicitly unset it with unset($var)
.
The only case where you can declare a variable without explicitly assigning a value is when it is a class property. For example:
class Example
{
public $var;
}
$ex = new Example;
var_dump($ex->var);
Here $var
is implicitly assigned a value of null when it is declared, and referring to it in your code will not cause an undefined variable notice.