Initializing Variables in PHP
Published: August 13, 2003
User Rating: 16,777,216.0 (256 votes)
It is a good practice to initialize your variables. However most of us forget to do them. Even those of us who have been coding for years, forget to initialize them. This creates errors or notices while running our scripts. This article deals with this issue and provide a solution to it.
How many times have you got this error on you php files ?
Notice: Undefined variable: variable_name in d:\www\test\file_name.php on line 3
I know I have, like a million times. I know I fail to intialiaze the variables like this:
$variable_name = '';
Well for a single variable, above line would just be sufficient to intialize it. But imagine have to intialize around 20-30 variables in a script. That could be a problem. And what about variable names used in the forms ?
If you usually use a form with show the values passed by the user and code something like this:
<input type='text' name='name' value=<?php echo $name; ?> />
and failed to intialize the
$name at the beginning of
the file, you bet you are going to get the error.
Now, imagine a form with 20 or more variable and you can have some idea of the mess that it would create.
So, we have to find a solution.