2

I always make my variables null in php now, but in the past I've just assigned values to them without making them null first. These variables are inner use variables, so they are getting content only from database or from php, but not from user input. Can I leave them this way, or should I make all of them null? I need to be sure that my script is safe.

Thank you for the help, sorry for my english!

  • By documentation: A variable is considered to be null if: it has been assigned the constant NULL OR it has not been set to any value yet OR it has been unset(). So yes it is safe to use null variable without make it null. http://php.net/manual/en/language.types.null.php – Samuel Kelemen Sep 19 '15 at 22:12
  • Declaring variables as NULL first is unnecessary, you're safe is you don't do it. The compiler knows what to do. – Juan Bonnett Sep 19 '15 at 22:13

1 Answers1

0

In your title, you asked if it was safe to use a variable without making it null first. However, in your question body, you ask whether it is ok to assign values to variables without making them null first.

If you try to assign values to a variable without making them null, it is perfectly fine.

$x = 1;
$y = 2;
$z = $x + $y; // 3

If you wanted to use variables without making them null, PHP will consider them null by default.

echo(is_null($a) ? "true" : "false"); // true
echo($a === null ? "true" : "false"); // true

But you will get a E_NOTICE if you try to use them without assigning it null.

$a = 1;
$c = $a + $b; // 1

PHP Notice: Undefined variable: b in ...

While this isn't a problem on PHP 5, you should be concerned if you are on PHP4. This could be security concern , as the register_globals directive is enabled by default in PHP 4.

The register_globals directive essentially allows anyone to set variables via requests. Elements in the $_REQUEST array are automatically registered as variables, if you do not set them to null yourself.

Community
  • 1
  • 1
Zsw
  • 3,920
  • 4
  • 29
  • 43
  • Thank you. I'm on php 5, but I will turn off register_globals by default. I tought that I will need to rewrite the whole code and make all the variables null. – user2921777 Sep 19 '15 at 22:59
  • @user2921777 If you are on PHP 5.4.0 or higher, register_globals have been removed so you don't have to worry. – Zsw Sep 19 '15 at 23:00