111

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
  • 52,016
  • 21
  • 93
  • 140
  • 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

208

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
  • 12,375
  • 12
  • 51
  • 73
andy.gurin
  • 3,884
  • 1
  • 21
  • 14
15

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,248
  • 2
  • 16
  • 22
RodolfoNeto
  • 483
  • 5
  • 4
13

Just omit the braces:

$this->$methodName($arg1, $arg2, $arg3);
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
4

You can also use call_user_func() and call_user_func_array()

Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
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,875
  • 14
  • 66
  • 96
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,942
  • 33
  • 16
2

In my case.

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

Using PHP SOAP.

Jason Plank
  • 2,336
  • 5
  • 31
  • 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.

ruleboy21
  • 5,510
  • 4
  • 17
  • 34
Snapey
  • 3,604
  • 1
  • 21
  • 19
  • 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