php - PhP 中是否有更优雅的方法将一个函数传递给另一个函数?

标签 php function

可以通过在字符串中传递函数名称 PHP pass function as param then call the function? 来完成

嗯,这非常粗糙。

没有类型检查

如果我重构函数名称,则包含变量的字符串也需要手动修复。如果我们有拼写错误,则不会在编译时进行检查。

这不像 vb.net 中那样有 addressOf 运算符。

这真的是在 PhP 中执行此操作的唯一方法吗?

我的意思是 lamda 函数看起来更理智。至少我们传递的变量实际上是一个 functio6 而不是字符串。

我错了吗?

正确的方法是使用 lambda 吗?

或者还有其他办法吗?

我可以像这样使用闭包

function getSelectedElements($textFile)
{

    $standardfuncline2= function (&$arout,$line)
    {
        standardfuncline1 ($arout,$line);
    };
    $result = getSelectedElementsCustomFunc ($textFile,$standardfuncline2);
    return $result;
}

而不是

$result = getSelectedElementsCustomFunc ($textFile,"standardfuncline1");

这似乎通过所有类型检查和其他东西得到了更证实。不过,有点太长了不是吗?

最佳答案

您可以将函数定义为闭包,即可以分配给变量或直接作为函数参数传递的匿名函数。以下示例取自PHP docs on callables :

Callback example using a Closure

<?php  
// Our closure
$double = function($a) {
    return $a * 2;
};

// This is our range of numbers
$numbers = range(1, 5);

// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

The above example will output:

2 4 6 8 10

以上的更多变体可以在PHP documentation on anonymous functions中找到.

引用现有函数时

对于以通常方式定义的函数,没有这样的解决方案,但您可以将它们封装为 Callable:

// Your already existing function:
function myFunc($arg) {
    echo "running myFunc with '$arg'.";
}

// The new Callable wrapper for it:
$myFunc = function ($arg) {
    myFunc($arg);
};

// Calling it (same as in first solution)
call_user_func($myFunc, 'test');

关于php - PhP 中是否有更优雅的方法将一个函数传递给另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38959506/

相关文章:

php - mysqli->commit 总是提交,即使语句中有错误

r - 将函数应用于向量中的每个元素组合

javascript - 如何在javascript函数中传递参数

javascript - JavaScript 中的货币转换器

c - 将大的多维数组传递给 C 中的函数

php - 拉维尔 5.1 "ReflectionException in Container.php line 737:..class does not exist"

php - 如何使用 PHP 从浏览器启动应用程序?

javascript - 在 JQuery 中比较两个相同的字符串返回 false

php - 尝试在 Debian 8 v-server 上将 phalcon 更新到 3.0

function - F# 中的模式匹配函数