Accessing a variable defined in a parent function

前端 未结 5 888
感动是毒
感动是毒 2020-12-03 00:10

Is there a way to access $foo from within inner()?

function outer()
{
    $foo = \"...\";

    function inner()
    {
        // pr         


        
5条回答
  •  情歌与酒
    2020-12-03 00:20

    I would like to mention that this is possibly not the best way to do coding, as you are defining a function within another. There is always a better option than doing in such a way.

    function outer()
    {
        global $foo;
        $foo = "Let us see and understand..."; // (Thanks @Emanuil)
    
        function inner()
        {
            global $foo;
            print $foo;
        }
    
        inner();
    }
    
    outer();
    

    This will output:-

    Let us see and understand...
    

    Instead of writing this way, you could have written the folowing code snippet:-

    function outer()
    {
        $foo = "Let us see improved way...";
    
        inner($foo);
    
        print "\n";
        print $foo;
    }
    
    function inner($arg_foo)
    {
        $arg_foo .= " and proper way...";
        print $arg_foo;
    }
    
    outer();
    

    This last code snippet will output:-

    Let us see improved way... and proper way...
    Let us see improved way...
    

    But at last, it is up to you always, as to which process you are going to use. So hope it helps.

提交回复
热议问题