Changing a global variable from inside a function PHP

后端 未结 4 1429
难免孤独
难免孤独 2020-12-01 05:15

I am trying to change a variable that is outside of a function, from within a function. Because if the date that the function is checking is over a certain amount I need it

相关标签:
4条回答
  • 2020-12-01 05:40

    Try this pass by reference

      $var = "01-01-10";
        function checkdate(&$funcVar){  
            if("Condition"){
                $funcVar = "01-01-11";
            }
        }
        checkdate($var);
    

    or Try this same as the above, keeping the function as same.

     $var = "01-01-10";
        function checkdate($funcVar){  
            if("Condition"){
                $funcVar = "01-01-11";
            }
        }
        checkdate(&$var);
    
    0 讨论(0)
  • 2020-12-01 05:42

    A. Use the global keyword to import from the application scope.

    $var = "01-01-10";
    function checkdate(){
        global $var;  
        if("Condition"){
            $var = "01-01-11";
        }
    }
    checkdate();
    

    B. Use the $GLOBALS array.

    $var = "01-01-10";
    function checkdate(){
        if("Condition"){
            $GLOBALS['var'] = "01-01-11";
        }
    }
    checkdate();
    

    C. Pass the variable by reference.

    $var = "01-01-10";
    function checkdate(&$funcVar){  
        if("Condition"){
            $funcVar = "01-01-11";
        }
    }
    checkdate($var);
    
    0 讨论(0)
  • 2020-12-01 05:47

    All the answers here are good, but... are you sure you want to do this?

    Changing global variables from within functions is generally a bad idea, because it can very easily cause spaghetti code to happen, wherein variables are being changed all over the system, functions are interdependent on each other, etc. It's a real mess.

    Please allow me to suggest a few alternatives:

    1) Object-oriented programming

    2) Having the function return a value, which is assigned by the caller.

    e.g. $var = checkdate();

    3) Having the value stored in an array that is passed into the function by reference

    function checkdate(&$values) { if (condition) { $values["date"] = "01-01-11"; } }

    Hope this helps.

    0 讨论(0)
  • 2020-12-01 05:59

    Just use the global keyword like so:

    $var = "01-01-10";
    function checkdate(){
         global $var;
    
         if("Condition"){
                $var = "01-01-11";
          }
    }
    

    Any reference to that variable will be to the global one then.

    0 讨论(0)
提交回复
热议问题