首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将参数传递给可调用函数

将参数传递给可调用函数
EN

Stack Overflow用户
提问于 2016-02-23 19:52:26
回答 4查看 13.6K关注 0票数 5

我好像不能让它起作用。我有一个函数,它接受一个我想要调用的参数。

protected function testFunc($param) {
    echo $param;
}

protected function testCall(callable $testFunc) {
    call_user_func($testFunc);
}

public function testProg($param) {
    $this->testCall([$this, 'testFunc']);
}

我试过了

$this->testCall([[$this, 'testFunc'], $param]);

$this->testCall([$this, 'testFunc($param)']);

$this->testCall('TestClass::testFunc($param));

闭包是我在这里唯一的选择吗?或者我如何将参数传递给可调用的函数

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-02-23 19:59:45

要调用方法(在您的示例中,function是类方法),您必须使用以下语法:

protected function testCall( $testFunc )
{
    call_user_func( array( $this, $testFunc ) );
}

要传递参数,必须使用以下语法:

protected function testCall( $testFunc, $arg )
{
    call_user_func( array( $this, $testFunc ), $arg );
}

(...)

$this->testCall( 'testFunc', $arg );

要传递多个参数,必须使用call_user_func_array

protected function testCall( $testFunc, array $args )
{
    call_user_func_array( array( $this, $testFunc ), $args );
}

(...)

$this->testCall( 'testFunc', array( $arg1, $arg2 ) );

编辑:

上面的代码运行良好,但是--正如注释中机智地指出的--前面的代码:

protected function testCall( callable $testFunc, $arg )

在上面的上下文中不起作用。

要使用它,必须在中修改上述方法和调用:

protected function testCall( callable $testFunc, $arg )
{
    call_user_func( $testFunc , $arg );
}

(...)

$this->testCall( array( $this, 'testFunc'), $arg );
票数 8
EN

Stack Overflow用户

发布于 2016-02-23 19:59:34

按如下方式修改您的代码

protected function testFunc($param) {
    echo $param;
}

protected function testCall(callable $testFunc, $param) {
    call_user_func($testFunc, $param);
}

public function testProg($param) {
    $this->testCall([$this, 'testFunc'], $param);
}

这样,第一个函数(testCall)接受第二个函数(testFunc)的参数。

只有在传递单个参数时,此代码才有效。如果希望传递数组,请使用call_user_func_array

票数 3
EN

Stack Overflow用户

发布于 2016-02-23 19:59:17

如果您知道参数的数量,请将它们传递给call_user_func

call_user_func($func_name, $arg1, $arg2)

如果您不知道参数的数量-将它们传递给call_user_func_array

call_user_func_array($func_name, [$arg1, $arg2, $arg3]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35576883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档