Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

haruntunay's avatar

Php - Accessing outer functions scope ?

I was wondering, how can compact function in php, can access it's surrounding functions scope ?

function call_me(){
    $name = "my_name";
    $age = 100;

    return compact("name", "age");
}

call_me();

// returns Array["name" => "harun",     "age" => 100 ];
//it can read the $name and $age variable from outer scope.

I though it has something to do with variable variables, and i tried to write my own version:

function my_compact_function(...$args){
    $arr = [];
    foreach($args as $arg){
        $arr[$arg] = $$arg;
    }

    return $arr;
}

//call my version of the compact;

function call_me(){
    $name = "my_name";
    $age = 100;

    return my_compact_function("name", "age");
}


call_me();

But it didn't work, i get an error saying $name and $age variables are not defined.

So, how does compact function access those variables ?

0 likes
2 replies
burlresearch's avatar

compact has access to these variables because they are in local scope (inside the function braces):

function call_me_compact() {
// vvv Function Scope vvv
    $name = "my_name";
    $age  = 100;

    return compact("name", "age"); // put variables from local scope into [array]
// ^^^ Function Scope ^^^
}

In your second example, you are calling a function with two strings and they are accessible in the $args list, take a look:

function my_compact_function(...$args) {
    print_r($args);
}

function call_me() {
    $name = "my_name";
    $age  = 100;

    return my_compact_function("name", "age");
}

// yielding: $args = [
//    [0] => name
//    [1] => age
// ]

The compact function actually returns a hashed array of variable names, and their values from local scope (via introspection).

1 like
burlresearch's avatar

If you changed your 2nd function to use the variables instead, it would look like this, but you would lose the knowledge of the names of the variables:

function my_compact_function(...$args) {
    print_r($args);
}

function call_me() {
    $name = "my_name";
    $age  = 100;
    return my_compact_function($name, $age);
}
//$args = Array (
//    [0] => my_name
//    [1] => 100
//)

Please or to participate in this conversation.