2016-01-13 169 views
-1

在php的另一个函数中调用函数的语法是什么? 我想是这样的:PHP:在另一个函数的参数中调用函数

function argfunction($a,$b,$c){ 
} 
function anotherfunction(argfunction($a,$b,$c), $d, $e) 
{ 
} 

我不是在anotherfunction

+0

这样的语法不存在.....这是根本不允许的语言.....它甚至应该做什么? –

+0

使用先前定义的函数的输出作为另一个函数的输入 - 它是不允许的? – shoestringfries

+2

@shoestringfries当你调用函数yes时,但不作为函数定义。所以呢:'另一个函数(argfunction($ a,$ b,$ c),$ d,$ e)'并且在你的定义中:'function anotherfunction($ fresult,$ d,$ e)' – Rizier123

回答

1

函数的参数应该是声明式的,即它们不应该做某事。

但是你可以用callable关键字做到这一点(PHP 5.4):

function argfunction($a,$b,$c){ 
    return $a+$b+$c; 
} 

function anotherfunction(callable $a_func, $a, $b, $c, $d, $e) { 
    // call the function we are given: 
    $abc = $a_func($a, $b, $c); 
    return $abc + $d * $e; 
} 

// call: 
anotherfunction ("argfunction", 1, 2, 3, 4, 5); // output: 26 

或者你也可以通过全功能的定义:

echo anotherfunction (function ($a, $b, $c) { 
     return $a+$b+$c; 
    }, 1, 2, 3, 4, 5); // output: 26 

或者,一个函数分配给一个变量,并传递:

$myfunc = function ($a, $b, $c) { 
    return $a+$b+$c; 
}; 
echo anotherfunction ($myfunc, 1, 2, 3, 4, 5); // output: 26 

但如果你只是想传递一个函数调用的结果到另一个功能,那么它更直截了当:

function anotherfunction2($abc, $d, $e) { 
    return $abc + $d * $e; 
} 

echo anotherfunction2 (argfunction(1, 2, 3), 4, 5); // output: 26 
+0

不知道这是不是正确的解释,但你的意思是函数'anotherfunction($ abc,$ d,$ e)'你真的将'argfunction'的参数串在一起?如果我在'anotherfunction'的函数定义中调用'argfunction',那么格式应该是什么? – shoestringfries

+1

不,在调用'anotherfunction2(argfunction(1,2,3),4,5);'时,PHP将首先调用* argfunction *参数* 1,2,3 *,这将返回6.然后PHP会调用* anotherfunction2 *将前面的结果作为第一个参数传递给它,所以传递的参数是* 6,4,5 *。这些被分配给变量* $ abc *(名字里有什么),* $ d *和* $ e *。 – trincot

1

定义再次调用​​没有道理,但我会假设你表达的方式不对你的想法。

你可能会寻找类似于回调的东西吗? 看看以下内容:herehere