2

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 ?

2
  • 6
    Your design is probably wrong. You should pass data into functions as arguments. Commented Feb 15, 2011 at 13:26
  • +1 for bad design but good question :) Commented Feb 15, 2011 at 13:30

4 Answers 4

4

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'];
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

This should have been pretty obvious, but it's right and worth a vote for simplicity :)
0

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.

Comments

0

You may want to read about Registry pattern, depending on your data, it may be useful or not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.