tags:

views:

68

answers:

2

Example: I have an variable like

$method = "doSomething";

Assume that I have an $myObject which knows a nonstatic, public method doSomething()

Could I then just call that method by doing this?

$myObject->$method();

Or is there another / better way?

+8  A: 

Yes, you can do that :

$myObject->$method();

This is called Variable functions


And here is the code that proves it :

class ClassA {
    public function method() {
        echo 'glop';
    }
}

$a = new ClassA();
$methodName = 'method';
$a->$methodName();

Gets you this output :

glop

Which means the method has been called ;-)


Another way would be to use call_user_func or call_user_func_array :

call_user_func(array($a, $methodName));

Here, you don't need this -- but you'd have to use that if your method was static, at least for PHP <= 5.2

Pascal MARTIN
Maybe add the link to `Variable Functions` in the manual: http://php.net/manual/en/functions.variable-functions.php
Gordon
@Gordon : Thanks for the suggestion ! I've edited my answer to add that link, and the term "Variable functions" :-)
Pascal MARTIN
Perfect answer, as usual. See my profile ;-)
openfrog
@openfrog : Thanks :-) And nice profile ;-)
Pascal MARTIN
My goal is to be the one who asked the most questions on SO ;-) lol
openfrog
lol ; good luck with that ^^
Pascal MARTIN
+4  A: 

Yes, however it is recommended that you first ensure the method exists prior to calling it:

if (method_exists(array($myObject, $method)) {
    $myObject->$method();
}
cballou
That would have been my next question ;-) great. Thanks man.
openfrog