106

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:

$this->{$methodName}($arg1, $arg2, $arg3);
VirtuosiMedia
  • 49,626
  • 21
  • 91
  • 139
  • Was it the original question ? I was looking for invoking a method dynamically and I found this question. It – Luc M Jul 30 '09 at 01:43
  • 5
    @Luc - It was the original question. It turns out that I did have the syntax right when I asked, but something else was wrong with my code, so it didn't work. – VirtuosiMedia Jul 30 '09 at 08:09
  • Related, possible duplicate (not sure which one would be a better target...) https://stackoverflow.com/questions/28954168/how-to-use-class-methods-as-callbacks – TylerH Feb 22 '22 at 21:35

8 Answers8

202

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

lxg
  • 11,188
  • 11
  • 43
  • 67
andy.gurin
  • 3,776
  • 1
  • 20
  • 14
14

You can use the Overloading in PHP: Overloading

class Test {

    private $name;

    public function __call($name, $arguments) {
        echo 'Method Name:' . $name . ' Arguments:' . implode(',', $arguments);
        //do a get
        if (preg_match('/^get_(.+)/', $name, $matches)) {
            $var_name = $matches[1];
            return $this->$var_name ? $this->$var_name : $arguments[0];
        }
        //do a set
        if (preg_match('/^set_(.+)/', $name, $matches)) {
            $var_name = $matches[1];
            $this->$var_name = $arguments[0];
        }
    }
}

$obj = new Test();
$obj->set_name('Any String'); //Echo:Method Name: set_name Arguments:Any String
echo $obj->get_name();//Echo:Method Name: get_name Arguments:
                      //return: Any String
Fabricio
  • 3,150
  • 2
  • 14
  • 21
RodolfoNeto
  • 473
  • 5
  • 3
13

Just omit the braces:

$this->$methodName($arg1, $arg2, $arg3);
Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
4

You can also use call_user_func() and call_user_func_array()

Peter Bailey
  • 103,526
  • 30
  • 178
  • 200
4

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.

Noah Goodrich
  • 24,292
  • 13
  • 64
  • 95
2

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

Community
  • 1
  • 1
David
  • 2,682
  • 29
  • 15
2

In my case.

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

Using PHP SOAP.

Jason Plank
  • 2,342
  • 4
  • 32
  • 40
user46637
  • 41
  • 1
1

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.

Snapey
  • 1,914
  • 1
  • 13
  • 12
  • If it's user defined content make sure you do much more than just trim the name! Such as... security check it! ;) – Erk Nov 18 '16 at 02:27
  • Somewhere on the internet, I detailed how to convert user entered utf8 into windows-safe characters. QuickBooks ran me through that wringer -- and why QB is no longer part of how I complete sales... – Krista K Dec 29 '17 at 06:50
  • Are you really allowing client to specify an input, that call dynamically some methods ?! I have no words – Mcsky May 03 '19 at 14:43
  • Obviously validated and checked that the class actually contains such a named method. There are many ways to check the value. It beats a lengthy switch statement. – Snapey May 03 '19 at 21:36