Chiraag Mundhe
Chiraag Mundhe

Reputation: 384

Changing the value of a variable that is a parameter in the parent scope

Is there any way to change the value of a parameter in the parent scope without passing it by reference to the child scope? I'd like to do something like this:

function foo($x = 5)
{
    bar();
    echo $x;  // Ideally should output 6
}

function bar()
{
    $x = 6;
}

foo();

In the scope of bar, I can get the value of $x by using debug_backtrace() or ReflectionFunction::getParameters, but I can't get a reference to $x!! Can this be done? I don't care if the solution is kind of a hack.

(To reiterate, I KNOW that I could just pass $x by reference to bar.)

Upvotes: 0

Views: 113

Answers (3)

leepowers
leepowers

Reputation: 38318

First off, foo() is not the parent scope of bar() - both functions exist in the global scope and the body of each function has it's own local scope.

The short answer to the question is as follows: no. Two alternatives:

Just assign the return value of bar() to the local variable `$x':

function foo($x = 5) {
    $x = bar();
    echo $x;  // Ideally should output 6
}
function bar() {
    return 6;
}
foo();

Encapsulate the logic of bar() into an external file (instead of a function) and include it:

bar.php:

<?php
 $x = 6;

foo.php

<?php
 function foo($x = 5) {
   include 'bar.php';
   echo $x;  // outputs '6'
 }

Upvotes: 1

Lee
Lee

Reputation: 13542

php has global variables. you can access a global from within a function by using the global keyword, or by using the $GLOBALS array directly.

Both techniques are described on the Variable Scope page of PHP's Manual.

function bar()
{
    global $x;

    $x = 6;
}

Upvotes: 0

user479911
user479911

Reputation:

You can probably do it using globals: http://no.php.net/manual/en/language.variables.scope.php

Upvotes: 0

Related Questions