if语句的可变范围问题(PHP) [英] Variable Scope issue with if statements ( PHP)
问题描述
好吧我似乎对PHP的变量范围存在误解,原谅我缺乏主题,因为我来自Java,C#背景。认为我可以通过将函数放在函数外部来使函数或if语句可以访问变量。以下是我要完成的内容:
Alright I seem to have a misconception with variable scope with PHP, forgive my lack of the subject as I come from a Java, C# background. Thinking I could make variables accessible to functions or if statements simply by placing it outside it. Below is a snippet of what I'm trying to accomplish:
foreach ($nm as $row=>$im) {
$itm_name = $im;
$lnk = $lnk_cty[$row];
if($mode == 'addMenu') {
$m = $m_id; //id will be coming from fresh insert of menu_name
} else {
$m = $_POST['mnu_add'][$row];
echo "MENU_ID: ".$m;
}
if($mode == 'addCat') {
$m = $c_id; //id will be coming from fresh insert of cat_name
} else {
$m = $_POST['cat_add'][$row];
}
//used for testing purposes
echo "item name: ".$itm_name ."<br />";
echo "lnk: ".$lnk ."<br />";
echo "m: ".$m ."<br />"; //$m is empty here, because its a new declaration as oppose to accessing $m value from if statement
$display_fields .= "<li>".$itm_name." ".$item."</li>";
$sql_array[] = '("' . $itm_name . '", "' . $lnk . '", ' . $m . ')'; // Add a new entry to the queue
}
现在我正在尝试do是使 $ m
变量值在if语句之外可以访问 $ m
变量 $ sql_array []
声明。在C#中,我只是在foreach循环之外声明一个变量并且能够使用它。在对此事进行一些阅读后,我发现使用全局或GLOBALS关键字只有在我的全局范围变量在foreach之前分配值并声明 global $ m
时才能使用在循环中获取该值。但是我的当前代码 $ m
属于if语句中的本地范围,并且每个人都不鼓励使用它们。现在,是否有更好的方法使 $ sql_array []
语句可以访问 $ m
?
Now what I'm trying to do is make the $m
variable values accessible outside the if statements its in to the $m
variable used in the $sql_array[]
statement. In C# I would simply declare a variable outside the foreach loop and be able to use it. After doing some reading on the matter I found that using the global or GLOBALS keywords would only work if my global scope variable is assign the value before the foreach, and declaring global $m
to obtain that value within the loop. But with my current code $m
is of a local scope within the if statements and everyone discourages using them. Now, is there a better method of making $m
accessible to the $sql_array[]
statement?
推荐答案
如果
语句块没有自己的范围。无论您分配给 $ m
的数据是什么,都必须为空。尝试调试诸如 $ _ POST
变量之类的内容。此外, $ m_id
在哪里被定义?也许它也是空的。
If
statement blocks do not have their own scope. Whatever data you are assigning to $m
must be empty to begin with. Try debugging things like your $_POST
variables. Also, where is $m_id
being defined? Maybe it is empty as well.
PHP 确实在函数,类方法等中有范围。但如果
语句没有自己的范围。例如,以下代码将回显您好!
:
PHP does have scope inside functions, class methods and the like. But if
statements do not have their own scope. For example, the following code would echo Hi there!
:
$bool = true;
if ($bool) {
$new_var = 'Hi there!';
}
echo $new_var;
读一下手册。
这篇关于if语句的可变范围问题(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!