在PhP中,有没有更优雅的方法可以将一个函数传递给另一个函数? [英] Is there a more elegant way to pass a function to another function in PhP?

查看:54
本文介绍了在PhP中,有没有更优雅的方法可以将一个函数传递给另一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过在字符串 PHP将函数作为参数传递,然后调用该函数?

那太荒谬了.

不进行类型检查

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

If I refactor the function name the string containing the variable need to be fixed too manually. If we have a typo it won't be checked on compile time.

这与vb.net中不存在addressOf运算符的情况类似.

It's not like in vb.net where we have addressOf operator.

这真的是在PhP中唯一做到这一点的方法吗?

Is this really the only way to do this in PhP?

我的意思是lamda函数看起来更加理智.至少我们传递的变量确实是functio6而不是字符串.

I mean the lamda function seems more sane. At least the variable we pass is really a functio6 and not a string.

我在这里错了吗?

使用lambda是正确的方法吗?

Is the right way to do this is to use lambda?

或者还有其他方法吗?

我可以使用这样的闭包

function getSelectedElements($textFile)
{

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

代替

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

所有类型检查和填充似乎更证明了这一点.但是,有点太长了吗?

That seems to be more proven with all type checking and stuffs. However, kind of too long isn't it?

推荐答案

您可以将函数定义为闭包,即可以分配给变量或直接作为函数参数传递的匿名函数.以下示例取自有关可调用对象的PHP文档:

You can define your function as a closure, i.e. an anonymous function which can be assigned to a variable or passed as a function argument directly. The following example is taken from the PHP docs on callables:

使用闭包的回调示例

<?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);
?>

上面的示例将输出:

2 4 6 8 10

可以在有关匿名函数的PHP文档中找到上述内容的更多变体.

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

There is no such solution for functions that are defined in the usual way, but you can encapsulate them as a 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中,有没有更优雅的方法可以将一个函数传递给另一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆