Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

php claims my defined variable is undefined

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:wampwwwfgwlphp-libfgwlshared.php on line 7

Notice: Undefined variable: msgs in C:wampwwwfgwlphp-libfgwlshared.php on line 7

Notice: Undefined variable: msgs in C:wampwwwfgwlphp-libfgwlshared.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<?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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...