PHP的声称我定义的变量是未定义的 [英] php claims my defined variable is undefined

查看:100
本文介绍了PHP的声称我定义的变量是未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的php有点生锈,但是这让我很困惑.我用谷歌搜索并阅读了所有可能看起来相关的stackoverflow问题,但这些问题似乎都包含合法的未定义变量.这使我相信我的问题是相同的,但是我并没有盯着那些简单的代码,而是将它简化为似乎可以解决任何问题.请有人给我我的工作帽,告诉我我做错了!

<?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();
?>

这给了我令人惊讶的输出:

注意:未定义的变量:第7行的C:\ wamp \ www \ fgwl \ php-lib \ fgwlshared.php中的消息

注意:未定义的变量:第7行的C:\ wamp \ www \ fgwl \ php-lib \ fgwlshared.php中的消息

注意:未定义的变量:第10行的C:\ wamp \ www \ fgwl \ php-lib \ fgwlshared.php中的消息

是的,这应该是共享文件,但此刻我将其剥离为粘贴的内容.有什么想法吗?

解决方案

它是在全局范围内定义的.如果要使用 global .

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?

解决方案

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

这篇关于PHP的声称我定义的变量是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆