Axalix
Axalix

Reputation: 2871

Why is a varibale "NULL" instead of being undefined?

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

Upvotes: 1

Views: 102

Answers (2)

pepe_botika69
pepe_botika69

Reputation: 67

"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."

Upvotes: 0

hanshenrik
hanshenrik

Reputation: 21493

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?

Upvotes: 1

Related Questions