How The Default Values Of Variables Are Uninitialized In PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

Uninitialized variables have a default value of their type depending on the context in which they are used - boolean default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.It is not necessary to initialize variables in PHP however it is a very good practice.

default values of variables are uninitialized in PHP

 

1.Integer.
$unset_integer += 10; // 0 + 10 => 10
var_dump($unset_integer); // outputs 'int(10)'


2.Boolean

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

 

3.String

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


4.Float/double

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


5.Array

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


6.Object

$unset_obj->data = 'data';
var_dump($unset_obj); // Outputs: object(stdClass)#1 (1) {  ["data"]=>  string(3) "data" }
 

Default value of an uninitialized variable is problematic in the case of using it in php script.
It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables.


 

Related Post