Accept function as parameter in PHP

后端 未结 8 758
Happy的楠姐
Happy的楠姐 2020-11-28 06:22

I\'ve been wondering whether is possible or not to pass a function as parameter in PHP; I want something like when you\'re programming in JS:

object.exampleM         


        
相关标签:
8条回答
  • 2020-11-28 06:53

    Tested for PHP 5.3

    As i see here, Anonymous Function could help you: http://php.net/manual/en/functions.anonymous.php

    What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function. As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.

    The function to do check:

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

    Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php

    call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );
    

    as it follows (in a similar, parameterless, way):

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

    Here's a class explaining how to do something similar :

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

    and an example of usage

    <?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)*/
    ?>
    
    0 讨论(0)
  • 2020-11-28 06:56

    Simple example using a class :

    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;
    
    
    });
    
    0 讨论(0)
  • 2020-11-28 06:57

    Just code it like this:

    function example($anon) {
      $anon();
    }
    
    example(function(){
      // some codes here
    });
    

    it would be great if you could invent something like this (inspired by Laravel Illuminate):

    Object::method("param_1", function($param){
      $param->something();
    });
    
    0 讨论(0)
  • 2020-11-28 06:59

    Just to add to the others, you can pass a function name:

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

    This will work in PHP4.

    0 讨论(0)
  • 2020-11-28 07:00

    You can also use create_function to create a function as a variable and pass it around. Though, I like the feeling of anonymous functions better. Go zombat.

    0 讨论(0)
  • 2020-11-28 07:01

    It's possible if you are using PHP 5.3.0 or higher.

    See Anonymous Functions in the manual.

    In your case, you would define exampleMethod like this:

    function exampleMethod($anonFunc) {
        //execute anonymous function
        $anonFunc();
    }
    
    0 讨论(0)
提交回复
热议问题