2

so imagine I have this PHP code

<?php
    $var = 10;

    function foo($var)
    {
        global $var;
        echo $var;
    }

    foo(2);
?>

The output here is 10. I want to know if there is a way to refer back to the function scope variable $var (which in my example has a value of 2).

3
  • 3
    No. Once you declare a variable global within a function, any previous "local" version of that variable name is gone. You'd have to store the param in some OTHER variable. Commented Jul 24, 2014 at 14:40
  • Can you not name the function parameter something other than the global variable name? Commented Jul 24, 2014 at 14:41
  • 1
    @crush indeed I can, but then I don't have a question for SO now do I :). Commented Jul 24, 2014 at 14:55

1 Answer 1

1

Maybe not an exact answer but here is a way:

$var = 10;

function foo($var)
{
    $array = get_defined_vars();
    global $var;
    echo $var;
    echo $array['var'];
}

foo(2);

You could also use func_get_arg() or func_get_args(), but whatever you do would need to be before the global statement.

Sign up to request clarification or add additional context in comments.

2 Comments

Yea, i thought that this might be the only way, but wanted to check if there's perhaps a keyword of some sort that drives the declaration back to function scope.
And actually this would be the same as $foo = $var; and then accessing $foo later.

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.