Downloads...
December 12, 2011
php: Initializing Variables
It is good practice to initialize all php variables and arrays. Until now there was no simple way of doing so. There is a 2003 solution by Amit Arora of digitalamit.com but which relies on GLOBAL variables which is not only a bad idea but supposedly GLOBALS will be deprecated in php version 6. My thanks to Amit for the inspiration!
The core problem is that variables cannot be called by reference. But arrays can and THAT is at the heart of the solution!
You still can't initialize variables globally but if one uses array elements in place of variables, then the solution is easy. I use arrays extensively. For example, on forms I put all the various error messages in an error array. Instead of using
$thisError
$thatError
I use
$error['this']
$error['that']
BTW, the function can also initialize to default values using a key=>value pair in an array. As the code is written, the default value is used only if the element is not initialized. To force the use of the default, comment out the if statement:
#
# // if(!isset($array[$k[0]])) { # if not initialized
# $array[$k[0]] = $key[$k[0]]; # set value
# // }
#
The code is amply commented so just download the file.
Enjoy!
Denny Schlesinger
Download initVars (1.2 KB)
Share this article with your followers