Default values of uninitialized variables

suggest change

Initialize variables before use. An uninitialized variable is treated as null, and the operator may then coerce that null. PHP 8 and later also warn about the undefined variable.

Unset AND unreferenced

var_dump($unset_var); // outputs NULL

Boolean

echo($unset_bool ? "true\n" : "false\n"); // outputs 'false'

String

$unset_str .= 'abc';
var_dump($unset_str); // outputs 'string(3) "abc"'

Integer

$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int); // outputs 'int(25)'

Float/double

$unset_float += 1.25;
var_dump($unset_float); // outputs 'float(1.25)'

Array

$unset_arr[3] = "def";
var_dump($unset_arr); //  outputs array(1) {  [3]=>  string(3) "def" }

Object

$unset_obj->foo = 'bar';

PHP 7 warned and created a stdClass. PHP 8 throws Error: Attempt to assign property "foo" on null.

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents