Perhaps you had to enter this:
class Test { public function testMethod() { echo 'called!'; } } $t = new Test(); $methodName = 'testMethod'; $t->$methodName();
If there is no - this kind of behavior is not standard for PHP, in order to be able to do this, you need to save an anonymous function in the class field, for example (PHP 5.3+):
class Test { public $testPropertyMethod; public function __construct() { $this->testPropertyMethod = function() { echo 'Hello closure'; }; } } $t = new Test(); $fieldName = 'testPropertyMethod'; $func = $t->$fieldName; $func();
But there is one thing here - by applying this approach calling a code of the form:
$t->$fieldName(); // выбросит ошибку
In order for the call to work correctly and in this case, it is necessary to determine (it sounds stupid, but I did not invent it) the "magic" __call method in our class, something like:
public function __call( $methodName, $arguments ) { $func = $this->$methodName; return call_user_func_array($func, $arguments); }
Now absolutely everything will work exactly as expected.
PS: A little help: $ an is not available in anonymous functions (although if necessary, of course, we can pass it on our own).