Reputation: 431
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
Upvotes: 2
Views: 588
Reputation: 212402
$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.
Upvotes: 2