Stupid question Re: Vars

It is my understanding that vars do not have to be declared before use in PHP.

I have a little test script that starts:

    <?php
      $testing; // declare without assigning
      echo "is null? ".is_null($testing); // checks if null
      echo "<br/>

Pretty straightforward, or so it seems. The output I get from this is:
Warning: Undefined variable $testing in index.php on line 3
is null? 1

So it executes, but why the error when I first check the variable? It would seem that if I don’t really need to declare then I should not get any error?

One more thing I noticed… I changed the line to read $testing = ‘’; // declare without assigning so now I do not get an error, but I also do not get any output from the is_null so what I get is is null? with nothing behind it…

Can anyone provide any insight into this?

Thanks for reading!
Jim

A variable by itself, i.e. the $testing; line, does nothing. This is not a declaration nor a reference to the variable. It doesn’t even produce any php bytecode (just confirmed), which is why it doesn’t produce an undefined error for that line.

That’s assigning an empty string to the variable.

The result is a false value, which when echoed doesn’t display anything (a true value when echoed results in a 1 being displayed.) You can use var_dump() to see the true/false value from the is_null() call.

1 Like

Hi PaganJim,

you don’t need to declare variables in PHP - it does not have variable declaration syntax. You can only initialize a variable by assigning a value to a new variable.

is_null strictly checks whether the variable value is null, it does not check whether the variable has been initialized.

If you want to check whether a variable has been initialized, you can use isset or empty, like this:

empty($testing);
isset($testing);

Both of which will evaluate to a boolean. Just be careful when you concatenate a boolean with a string in PHP, since a boolean of value false concatenates to an empty string.

1 Like

Thank you very much for reading and the replies. Both are very helpful and greatly appreciated.

But, it throwing and error like Warning: Undefined variable $testing in index.php on line 9 kinda threw me for a loop I guess. I had read that there was not need to declare vars. I guess I just didn’t expect it to be a no-no. I expected it to just give it a null value on it’s own and keep running.

I guess I still have a PERL mindset and I will have to get away from that. It may take a little work and just being more careful. Anyway, thank you to both of you. It really is appreciated.
Jim

Sponsor our Newsletter | Privacy Policy | Terms of Service