2

Is there a way to pass a variable into a function scope in PHP similar to Javascript? Here's what I understand thus far:

// Simple Function
$hello_world = function(){
    echo 'Hello World 1';
};
$hello_world();

// Using Global Variable
$text = 'Hello World 2';
$hello_world = function(){
    // Need to Add Global
    global $text;
    // Adding Text
    echo $text;
};
$hello_world();


// Dynamically Created Functions
$function_list = [];
// Function to Create Dynamic Function
function create_dynamic_function($function_name,$response_text){
    global $function_list;
    $function_list[$function_name] = function(){
        echo $response_text;    // Want to Echo the Input $response_text, but it cannot find it
    };
}

create_dynamic_function('Hello','Hello World 3');
$function_list['Hello'](); // Doesn't Work

I would like to pass the response text into the newly generated function without have to check what is response_text. it could be a string, int, boolean, object etc

1
  • function() use($response_text) Commented Nov 4, 2017 at 22:42

1 Answer 1

2

$response_text isn't in scope inside the anonymous function that you're creating:

function create_dynamic_function($function_name,$response_text){
    global $function_list;
    $function_list[$function_name] = function() use ($response_text) {
        echo $response_text;    // Want to Echo the Input $response_text, but it cannot find it
    };
}

For reference, arguments passed to an anonymous function are values applied when that function is executed; arguments passed via use are values applied when the function is defined.

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

1 Comment

Thank a lot :). I'm just a newbie PHP coder, and most of my coding knowledge is from Javascript. I figure PHP is similar to Javascript enough. I will mark this as accepted answer when I am able.

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.