1

Im having trouble getting a function within a function working, do you think what I have below is done rigth? Im not getting the expected results, if you could shed some light on functions within functions i would appriciete it.

thanks

function test1 ()

{

    global x;

    $x=123;

    function test2()
    {
    echo $x;
    }

    test2();

}
1
  • 2
    What is your expected result? This construct makes hardly sense. What do you need it for? Commented Dec 4, 2009 at 1:38

3 Answers 3

3

It works, but the scope of test2() is limited. For example, this works:

[wally@zf ~]$ cat y.php
<?php
function test1 ()
{
        global $x;
        $x=123;

        function test2()
        {
                global $x;
                echo $x;
        }

        test2();
}

test1();
?>
[wally@zf ~]$ php -f y.php
123[wally@zf ~]$
Sign up to request clarification or add additional context in comments.

2 Comments

wallyk thank you for the insight, this indeed works now. can you explain why you require x to be redeclared once again as a global in the second function?
It's so that $x can be seen outside the respective functions. If $x=123 were set outside test1(), there would be no need for test1() to have global $x.
0

Can't you just include it as another function outside the first function (test1)? I'm having trouble picturing a use-case for this.

Comments

0

You're not calling the function test2 so there's no reason for it to echo $x.

besides, you should construct the function outside, there's no added value in this case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.