views:

292

answers:

4

My php is a little rusty but this is boggling my mind right now. I googled this and read all the stackoverflow questions I could find that looked related, but those all seemed to have legitimate undefined variables in them. That leads me to believe that mine is the same problem, but no amount of staring at the simple bit of code I have reduced this to seems to get me anywhere. Please someone give me my dunce cap and tell me what I did wrong!

<?php
//test for damn undefined variable error

$msgs = "";

function add_msg($msg){
  $msgs .= "<div>$msg</div>";
}
function print_msgs(){
  print $msgs;
}

add_msg("test");
add_msg("test2");
print_msgs();
?>

This gives me the following, maddening output:

Notice: Undefined variable: msgs in C:\wamp\www\fgwl\php-lib\fgwlshared.php on line 7

Notice: Undefined variable: msgs in C:\wamp\www\fgwl\php-lib\fgwlshared.php on line 7

Notice: Undefined variable: msgs in C:\wamp\www\fgwl\php-lib\fgwlshared.php on line 10

Yes, this is supposed to be a shared file, but at the moment I have stripped it down to just what I pasted. Any ideas?

+6  A: 

It's defined at the global scope. Use global if you want to use it.

Ignacio Vazquez-Abrams
yep. that did it. looks like i need to brush up on scopes in php. thanks!
tedders
+7  A: 
<?php
$msgs = "";

function add_msg($msg){
  global $msgs;
  $msgs .= "<div>$msg</div>";
}
function print_msgs(){
  global $msgs;
  print $msgs;
}

add_msg("test");
add_msg("test2");
print_msgs();
?>

global tells that PHP need to use the global variable in the local function scope.

Veger
I upvoted this because it answers the question, but I have to add that it's extremely bad practice to use global variables. think globally, act in local scope. They don't print it on shirts for no good reason.
Kris
thanks for the example.
tedders
you're welcome. But keep the advice Kris gave in your mind. For this example it is clear what is happening, but for big(ger) applications, it might become messy and unclear who is fiddling with which variables and therefore error prone.
Veger
A: 

if you don't want to use globals, you can jast use

 function add_msg($msg)
   {
         echo  "<div>$msg</div>";
   }
    add_msg("test");
    add_msg("test2");

function, the result will be the same.

Syom
+1  A: 

Using globals for something like this is a poor practice. Consider an alternate approach such as the following:

class MessageQueue {
  private static $msgs;


  public static function add_msg($msg){
    self::$msgs .= "<div>$msg</div>"; 
  }
  public static function print_msgs(){
    print self::$msgs;
  }
}


MessageQueue::add_msg("test");
MessageQueue::add_msg("test2");
MessageQueue::print_msgs();
Frank Farmer