Variable Scope issue with if statements ( PHP)

2019-02-06 06:37发布

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 
}

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?

2条回答
对你真心纯属浪费
2楼-- · 2019-02-06 07:22

Its true that if statements does NOT have scope , but It seems that there is a problem with the Scope (piece of code in braces)..in the below code snippet the expected result is : $z[0] = 0, $z[1] = 1 but the Actual output obtained is $z[0] = 100; and $z[1] is undefined. The PHP used is from Apache Friends distribution

<?php

$x = 0;
$y = 1;
$z[0]=100;

if($x!=0){
    $z[0]=1;
    $z[1]=2;
    $z[2]=3;
    $z[3]=4;
}else{
    if($y == 0){
        $a =1;
    }else{
        global $z;
        echo $z[0];
        echo $z[1];
    }
}

?>
查看更多
做个烂人
3楼-- · 2019-02-06 07:33

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 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;

Have a read in the manual.

查看更多
登录 后发表回答