php PHP传递函数名作为参数然后调用函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/627775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP pass function name as param then call the function?
提问by JD Isaacks
I need to pass a function as a parameter to another function and then call the passed function from within the function...This is probably easier for me to explain in code..I basically want to do something like this:
我需要将一个函数作为参数传递给另一个函数,然后从函数内部调用传递的函数......这对我来说在代码中解释起来可能更容易......我基本上想做这样的事情:
function ($functionToBeCalled)
{
call($functionToBeCalled,additional_params);
}
Is there a way to do that.. I am using PHP 4.3.9
有没有办法做到这一点..我使用的是 PHP 4.3.9
Thanks!
谢谢!
回答by Paolo Bergantino
I think you are looking for call_user_func.
我想你正在寻找call_user_func。
An example from the PHP Manual:
PHP手册中的一个例子:
<?php
function barber($type) {
echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>
回答by Stewart Robinson
In php this is very simple.
在 php 中,这很简单。
<?php
function here() {
print 'here';
}
function dynamo($name) {
$name();
}
//Will work
dynamo('here');
//Will fail
dynamo('not_here');
回答by TJ L
function foo($function) {
$function(" World");
}
function bar($params) {
echo "Hello".$params;
}
$variable = 'bar';
foo($variable);
Additionally, you can do it this way. See variable functions.
此外,您可以这样做。请参阅变量函数。
回答by TJ L
You could also use call_user_func_array(). It allows you to pass an array of parameters as the second parameter so you don't have to know exactly how many variables you're passing.
您也可以使用call_user_func_array(). 它允许您将参数数组作为第二个参数传递,因此您不必确切知道要传递多少个变量。
回答by mercurial
I know the original question asked about PHP 4.3, but now it's a few years later and I just wanted to advocate for my preferred way to do this in PHP 5.3 or higher.
我知道最初的问题是关于 PHP 4.3 的,但现在是几年后,我只是想提倡我在 PHP 5.3 或更高版本中执行此操作的首选方法。
PHP 5.3+ now includes support for anonymous functions (closures), so you can use some standard functional programming techniques, as in languages like JavaScript and Ruby (with a few caveats). Rewriting the call_user_func example above in "closure style" would look like this, which I find more elegant:
PHP 5.3+ 现在包括对匿名函数(闭包)的支持,因此您可以使用一些标准的函数式编程技术,如 JavaScript 和 Ruby 等语言(有一些警告)。以“闭包风格”重写上面的 call_user_func 示例看起来像这样,我觉得它更优雅:
$barber = function($type) {
echo "You wanted a $type haircut, no problem\n";
};
$barber('mushroom');
$barber('shave');
Obviously, this doesn't buy you much in this example - the power and flexibility comes when you pass these anonymous functions to other functions (as in the original question). So you can do something like:
显然,在这个例子中,这并没有给你带来太多好处 - 当你将这些匿名函数传递给其他函数时(如原始问题中所示),功能和灵活性就来了。因此,您可以执行以下操作:
$barber_cost = function($quantity) {
return $quantity * 15;
};
$candy_shop_cost = function($quantity) {
return $quantity * 4.50; // It's Moonstruck chocolate, ok?
};
function get_cost($cost_fn, $quantity) {
return $cost_fn($quantity);
}
echo '3 haircuts cost $' . get_cost($barber_cost, 3) . "\n";
echo '6 candies cost $' . get_cost($candy_shop_cost, 6) . "\n";
This could be done with call_user_func, of course, but I find this syntax much clearer, especially once namespaces and member variables get involved.
当然,这可以通过 call_user_func 来完成,但我发现这种语法更清晰,尤其是在涉及命名空间和成员变量时。
One caveat: I'll be the first to admit I don't know exactly what's going on here, but you can't always call a closure contained in a member or static variable, and possibly in some other cases. But reassigning it to a local variable will allow it to be invoked. So, for example, this will give you an error:
一个警告:我将是第一个承认我不知道这里到底发生了什么的人,但是你不能总是调用包含在成员或静态变量中的闭包,也可能在其他一些情况下。但是将它重新分配给局部变量将允许它被调用。因此,例如,这会给您一个错误:
$some_value = \SomeNamespace\SomeClass::$closure($arg1, $arg2);
But this simple workaround fixes the issue:
但是这个简单的解决方法解决了这个问题:
$the_closure = \SomeNamespace\SomeClass::$closure;
$some_value = $the_closure($arg1, $arg2);
回答by w411 3
If you need pass function with parameter as parameter, you can try this:
如果您需要以参数为参数的传递函数,您可以试试这个:
function foo ($param1){
return $param1;
}
function bar ($foo_function, $foo_param){
echo $foo_function($foo_param);
}
//call function bar
bar('foo', 'Hi there'); //this will print: 'Hi there'
Hope it'll be helpful...
希望它会有所帮助...
回答by drjorgepolanco
If you want to do this inside a PHP Class, take a look at this code:
如果您想在 PHP 类中执行此操作,请查看以下代码:
// Create a sample class
class Sample
{
// Our class displays 2 lists, one for images and one for paragraphs
function __construct( $args ) {
$images = $args['images'];
$items = $args['items'];
?>
<div>
<?php
// Display a list of images
$this->loop( $images, 'image' );
// notice how we pass the name of the function as a string
// Display a list of paragraphs
$this->loop( $items, 'content' );
// notice how we pass the name of the function as a string
?>
</div>
<?php
}
// Reuse the loop
function loop( $items, $type ) {
// if there are items
if ( $items ) {
// iterate through each one
foreach ( $items as $item ) {
// pass the current item to the function
$this->$type( $item );
// becomes $this->image
// becomes $this->content
}
}
}
// Display a single image
function image( $item ) {
?>
<img src="<?php echo $item['url']; ?>">
<?php
}
// Display a single paragraph
function content( $item ) {
?>
<p><?php echo $item; ?></p>
<?php
}
}
// Create 2 sample arrays
$images = array( 'image-1.jpg', 'image-2.jpg', 'image-3.jpg' );
$items = array( 'sample one', 'sample two', 'sample three' );
// Create a sample object to pass my arrays to Sample
$elements = { 'images' => $images, 'items' => $items }
// Create an Instance of Sample and pass the $elements as arguments
new Sample( $elements );

