Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I am creating a custom module and I want to use a couple variables as counters, here is an example:

 $variable1 = 0;
 $variable2 = 0;

 function1(){
   $variable1++;
 }

 function2(){
   $variable2++;
 }

 function3(){
   $message = "Nodes".$variable1;
   $message .= "Users".$variable2;
   drupal_set_message($message);
 }

There is a loop in these functions. My problem is that I get an Undefined variable Error. Not sure if there is a Drupal protocol for doing this?

share|improve this question
you havent mentioned where in the code you are getting the error – subhojit777 Jan 19 at 21:52
It's when I run the code. I get a drupal error at the top of the page saying Undefined variable and it points to the function3 variables. It seems I can't access those variables? – Brian Jan 19 at 21:54
You have incorrect code in your question.. please correct the code – subhojit777 Jan 19 at 22:07
why do you need to create 2 functions with counters? where the functions is called? – neok Jan 19 at 22:43
1  
The question as asked is not about Drupal. The reason the code is not working is that in PHP local variables don't override the global variables. In its current form, this question is off-topic for Drupal Answers. – kiamlaluno Jan 20 at 0:04

closed as off topic by kiamlaluno Jan 20 at 0:05

Questions on Drupal Answers are expected to relate to Drupal within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

This has nothing to do with Drupal. You need to learn PHP.

Your code is not valid PHP: 1) You do not declare your functions correctly. 2) You try to use global variables in a local scope without declaring them to be global. Here is your code corrected:

$variable1 = 0;
$variable2 = 0;

function f1() {
   global $variable1;
   $variable1++;
}

function f2(){
   global $variable2;
   $variable2++;
}

function f3(){
   global $variable1, $variable2;
   $message = 'Nodes ' . $variable1;
   $message .= ' Users ' . $variable2;
   drupal_set_message($message);
}

The "Undefined variable Error" is due to error #2.

share|improve this answer
I don't know why one of the examples is not showing but this was tried. LOOKS LIKE WE BOTH NEED TO LEARN PHP! – Brian Jan 19 at 23:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.