在PHP中接受函数作为参数

时间:2010-04-23 16:56:30

标签: php function

我一直想知道是否可以在PHP中将函数作为参数传递;我想要一些像你在JS编程的东西:

object.exampleMethod(function(){
    // some stuff to execute
});

我想要的是在exampleMethod中的某个地方执行该功能。这可能在PHP吗?

8 个答案:

答案 0 :(得分:131)

如果您使用的是PHP 5.3.0或更高版本,则可以使用。

请参阅手册中的Anonymous Functions

在您的情况下,您可以像这样定义exampleMethod

function exampleMethod($anonFunc) {
    //execute anonymous function
    $anonFunc();
}

答案 1 :(得分:41)

只是要添加到其他人,您可以传递一个函数名称:

function someFunc($a)
{
    echo $a;
}

function callFunc($name)
{
    $name('funky!');
}

callFunc('someFunc');

这适用于PHP4。

答案 2 :(得分:15)

您还可以使用create_function将函数创建为变量并传递它。虽然,我更喜欢anonymous functions的感觉。去zombat。

答案 3 :(得分:12)

就像这样编码:

function example($anon) {
  $anon();
}

example(function(){
  // some codes here
});
如果你能发明这样的东西(灵感来自Laravel Illuminate),那就太棒了:

Object::method("param_1", function($param){
  $param->something();
});

答案 4 :(得分:5)

根据@ zombat的回答,最好首先验证匿名函数:

function exampleMethod($anonFunc) {
    //execute anonymous function
    if (is_callable($anonFunc)) {
        $anonFunc();
    }
}

或者从PHP 5.4.0开始验证参数类型:

function exampleMethod(callable $anonFunc) {}

答案 5 :(得分:3)

PHP VERSION> = 5.3.0

示例1:基本

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

示例2:std对象

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

示例3:非静态类调用

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

示例4:静态类调用

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

答案 6 :(得分:2)

使用类的简单示例:

class test {

    public function works($other_parameter, $function_as_parameter)
    {

        return $function_as_parameter($other_parameter) ;

    }

}

$obj = new test() ;

echo $obj->works('working well',function($other_parameter){


    return $other_parameter;


});

答案 7 :(得分:2)

为PHP 5.3测试

正如我在此处看到的,匿名函数可以帮助您: http://php.net/manual/en/functions.anonymous.php

你可能需要什么,并且在如何传递函数而不将其包装在动态创建的函数之前,它不会被说出来。 正如您稍后将看到的,您需要将函数的名称作为参数传递给字符串,检查其“callability”然后调用它。

要检查的功能:

if( is_callable( $string_function_name ) ){
    /*perform the call*/
}

然后,要调用它,请使用这段代码(如果您还需要参数,请将它们放在数组中),如下所示:http://php.net/manual/en/function.call-user-func.php

call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );

如下(以类似的,无参数的方式):

    function funToBeCalled(){
        print("----------------------i'm here");
    }
    function wrapCaller($fun){
        if( is_callable($fun)){
            print("called");
            call_user_func($fun);
        }else{
            print($fun." not called");
        }
    }

    wrapCaller("funToBeCalled");
    wrapCaller("cannot call me");

这是一个解释如何做类似事情的课程:

<?php
class HolderValuesOrFunctionsAsString{
    private $functions = array();
    private $vars = array();

    function __set($name,$data){
        if(is_callable($data))
            $this->functions[$name] = $data;
        else
            $this->vars[$name] = $data;
    }

    function __get($name){
        $t = $this->vars[$name];
        if(isset($t))
            return $t;
        else{
            $t = $this->$functions[$name];
            if( isset($t))
                return $t;
        }
    }

    function __call($method,$args=null){
        $fun = $this->functions[$method];
        if(isset($fun)){
            call_user_func_array($fun,$args);
        } else {
            // error out
            print("ERROR: Funciton not found: ". $method);
        }
    }
}
?>

以及使用示例

<?php
    /*create a sample function*/
    function sayHello($some = "all"){
    ?>
         <br>hello to <?=$some?><br>
    <?php
    }

    $obj = new HolderValuesOrFunctionsAsString;

    /*do the assignement*/
    $obj->justPrintSomething = 'sayHello'; /*note that the given
        "sayHello" it's a string ! */

    /*now call it*/
    $obj->justPrintSomething(); /*will print: "hello to all" and
        a break-line, for html purpose*/

    /*if the string assigned is not denoting a defined method
         , it's treat as a simple value*/
    $obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';

    echo $obj->justPrintSomething; /*what do you expect to print?
        just that string*/
    /*N.B.: "justPrintSomething" is treated as a variable now!
        as the __set 's override specify"*/

    /*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
     $obj->justPrintSomething("Jack Sparrow");


     /*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/

     $obj->justPrintSomething( $obj->justPrintSomething );
         /*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/

    /*in fact, "justPrintSomething" it's a name used to identify both
         a value (into the dictionary of values) or a function-name
         (into the dictionary of functions)*/
?>