PHP在更多函数之间传递变量
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 $variable; 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 ?
我需要将大约30个变量传递给3个函数,例如 p>
displayform() - 从DB中提取一些表单数据,需要将一些表单数据输入表单。 p>
checkform() - 哪个 检查所有数据是否输入正确。 p>
errors() - 这将显示错误(如果有) p>
processform() - 此过程所有数据 并将它们存储到DB p>
现在我正在使用GLOBAL $变量; 在函数之间传递这些变量,但是我必须在函数begin处将每个变量声明为全局并且导致一个大文件,所以我只想知道有没有办法将变量声明为全局变量(最好只有一次)所以 所有功能都可以使用它们吗? p> div>
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.
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.