繁体   English   中英

PHP 通过 function 名称作为参数然后调用 function?

[英]PHP pass function name as param then call the function?

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

有没有办法做到这一点.. 我正在使用 PHP 4.3.9

谢谢!

我认为您正在寻找call_user_func

PHP 手册中的示例:

<?php
function barber($type) {
    echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

在 php 中,这非常简单。

<?php

function here() {
  print 'here';
}


function dynamo($name) {
 $name();
}

//Will work
dynamo('here');
//Will fail
dynamo('not_here');
function foo($function) {
  $function(" World");
}
function bar($params) {
  echo "Hello".$params;
}

$variable = 'bar';
foo($variable);

此外,您可以这样做。 请参阅变量函数

我知道最初的问题是关于 PHP 4.3,但现在已经过了几年,我只是想在 PHP 5.3 或更高版本中提倡我首选的方法。

PHP 5.3+ 现在包括对匿名函数(闭包)的支持,因此您可以使用一些标准的函数式编程技术,例如 JavaScript 和 Ruby 等语言(有一些警告)。 用“闭包风格”重写上面的 call_user_func 示例看起来像这样,我发现它更优雅:

$barber = function($type) {
    echo "You wanted a $type haircut, no problem\n";
};

$barber('mushroom');
$barber('shave');

显然,在这个例子中这并没有给你带来太多好处——当你将这些匿名函数传递给其他函数时(如原始问题中所示),功能和灵活性就来了。 因此,您可以执行以下操作:

$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";

当然,这可以使用 call_user_func 来完成,但我发现这种语法更加清晰,尤其是在涉及命名空间和成员变量时。

一个警告:我将是第一个承认我不确切知道这里发生了什么的人,但你不能总是调用包含在成员或 static 变量中的闭包,并且可能在其他一些情况下。 但是将其重新分配给局部变量将允许调用它。 因此,例如,这会给您一个错误:

$some_value = \SomeNamespace\SomeClass::$closure($arg1, $arg2);

但是这个简单的解决方法解决了这个问题:

$the_closure = \SomeNamespace\SomeClass::$closure;
$some_value = $the_closure($arg1, $arg2);

您也可以使用call_user_func_array() 它允许您将参数数组作为第二个参数传递,因此您不必确切知道要传递的变量数量。

如果你需要通过 function 参数作为参数,你可以试试这个:

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'

phpfiddle 示例

希望它会有所帮助...

如果您想在 PHP Class 中执行此操作,请查看以下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM