Dynamic class method invocation in PHP

后端 未结 8 1899
感动是毒
感动是毒 2020-11-28 05:05

Is there a way to dynamically invoke a method in the same class for PHP? I don\'t have the syntax right, but I\'m looking to do something similar to this:

$t         


        
相关标签:
8条回答
  • 2020-11-28 05:14

    You can store a method in a single variable using a closure:

    class test{        
    
        function echo_this($text){
            echo $text;
        }
    
        function get_method($method){
            $object = $this;
            return function() use($object, $method){
                $args = func_get_args();
                return call_user_func_array(array($object, $method), $args);           
            };
        }
    }
    
    $test = new test();
    $echo = $test->get_method('echo_this');
    $echo('Hello');  //Output is "Hello"
    

    EDIT: I've edited the code and now it's compatible with PHP 5.3. Another example here

    0 讨论(0)
  • 2020-11-28 05:20

    In my case.

    $response = $client->{$this->requestFunc}($this->requestMsg);
    

    Using PHP SOAP.

    0 讨论(0)
  • 2020-11-28 05:22

    You can also use call_user_func() and call_user_func_array()

    0 讨论(0)
  • 2020-11-28 05:24

    There is more than one way to do that:

    $this->{$methodName}($arg1, $arg2, $arg3);
    $this->$methodName($arg1, $arg2, $arg3);
    call_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));
    

    You may even use the reflection api http://php.net/manual/en/class.reflection.php

    0 讨论(0)
  • 2020-11-28 05:28

    If you're working within a class in PHP, then I would recommend using the overloaded __call function in PHP5. You can find the reference here.

    Basically __call does for dynamic functions what __set and __get do for variables in OO PHP5.

    0 讨论(0)
  • 2020-11-28 05:30

    Still valid after all these years! Make sure you trim $methodName if it is user defined content. I could not get $this->$methodName to work until I noticed it had a leading space.

    0 讨论(0)
提交回复
热议问题