PHP passing variables between more function
I have about 30 variables that I need to pass to 3 functions e.g.
displayform() - where some form data is pulled out from DB and some needs to be entered into the form.
checkform() - which checks if all data is entered properly.
errors() - this will display errors (if any)
processform()- this process all data and store them to DB
Now I am using GLOBAL $var开发者_如何学JAVAiable; to pass those variables between functions, but than I have to declare each variable as global at the function begin and that results in a big file, so I just want to know is there a way to declare variables as globals (preferably only once) so that all functions can use them ?
You can try putting all the variables into an associative array and just passing this array between functions, like:
$omgArray = array();
$omgArray['lolVar1'] = lolVar1;
$omgArray['wowVar3'] = wowVar3;
yeaaaFunction($omgArray);
function yeaaaFunction($omgArray){
echo $omgArray['lolVar1'] . $omgArray['wowVar3'];
}
30 variables? Apart from 30 variables being horrible to maintain, having 30 global variables is even worse. You will go crazy one day...
Use an array and pass the array to the functions as argument:
$vars = array(
'var1' => 'value1',
'var2' => 'value2',
///...
);
displayform($vars);
//etc.
Learn more about arrays.
I have a similar scenario where I wrote a class lib for form handling similar to yours. I store all form data into a single array internally in the form class.
When moving form data outside the class I serialize the array into JSON format. The advantage of the JSON format (over PHP's own serialized format) is that it handles nested arrays very well. You can also convert the character set for all the form fields in one call.
In my application I store all form data as a JSON string in the database. But I guess it all depends on your needs.
You may want to read about Registry pattern, depending on your data, it may be useful or not.
精彩评论