to Global Variables inside functions

蹲街弑〆低调 提交于 2020-01-06 07:27:13

问题


I have problem to Global Variables inside functions

<?php
    function main(){
        $var = "My Variable";
        function sub() {
            GLOBAL $var;
            echo $var; // Will show "My Variable"
        }
        sub();
        echo $var; // Will show "My Variable" 
    }
    main();
    sub(); // Will not show and I will sub() cant use outside main() function
?>
  1. I just want to global $var inside sub functions
  2. sub() will not work outside main() function

I tied to use GLOBAL but it show nothing ... Any ?


回答1:


Not sure if i understand what you want, but your $var is not global. its a local variable inside main()

a variable is only global, if you declare it outside of a function or class.

<?php
    $var = "My Variable"; // made $var global
    function main(){
        //removed $var here
        function sub() {
            global $var;
            echo $var; // Will show "My Variable"
        }
        sub();
        echo $var; // Will throw notice:  Undefined variable: var
    }
    main();
    sub(); // Will show "My Variable"
?>

why would you declare a method inside a method to call it from there?

maybe something like this is what you want...

<?php
   //$var = "My Variable";
    function main(){
        $var = "My Variable";
        $sub = function($var) {
            echo "sub: ".$var; // Will show "sub: My Variable"
        };
        $sub($var);
        echo "main: ".$var; //  Will show "main: My Variable"
    }
    main();
    // sub(); // Will not work
    // $sub(); // Will not work
?>



回答2:


You do not assing a value to the global scope variable $var.
Only main() assigns a value to a variable called $var but only in main()'s scope. And only main()'s echo $var; actually prints the value. Both calls to sub() do not produce output.
try it with

<?php
function main(){
    $var = "My Variable"; 
    function sub() {
      GLOBAL $var;
      echo 'sub: ', $var, "\n";
    }
    sub();
    echo 'main: ', $var, "\n";
}
main();
sub();

the output is

sub: 
main: My Variable
sub: 

and please have a read of https://en.wikipedia.org/wiki/Dependency_injection ;-)



来源:https://stackoverflow.com/questions/15380057/to-global-variables-inside-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!