【问题标题】:Passing Variables into PHP Function Scope将变量传递到 PHP 函数作用域
【发布时间】:2018-04-17 09:32:38
【问题描述】:

有没有办法将变量传递到 PHP 中类似于 Javascript 的函数范围?到目前为止,这是我的理解:

// 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

我想将响应文本传递给新生成的函数,而不必检查什么是 response_text。它可以是字符串、整数、布尔值、对象等

【问题讨论】:

  • function() use($response_text)

标签: php


【解决方案1】:

$response_text 不在您正在创建的匿名函数的范围内:

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
    };
}

作为参考,传递给匿名函数的参数是执行该函数时应用的值;通过use 传递的参数是定义函数时应用的值。

【讨论】:

  • 非常感谢:)。我只是一个新手 PHP 编码器,我的大部分编码知识来自 Javascript。我认为 PHP 与 Javascript 足够相似。我会在可能的情况下将此标记为已接受的答案。
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
相关资源
最近更新 更多