如何使用变量作为对象方法的名称?

Here is my code:

$method_name = 'mymethod()';
$obj = new Myclass();
$obj->$method_name;

As you see I've used $method_name as the name of a method. But it throws this error message:

Undefined property: app\classes\Myclass::$mymethod()

How can I fix it?

You should avoid using string to do reflection... And use the ReflectionClass and the ReflectionMethod.

However, the proper way of doing it is:

$method_name = 'mymethod';
$obj = new Myclass();
$obj->$method_name();

You set method name to be mymethod(), that is invalid.

Set it just to mymethod:

$method_name = 'mymethod';
$obj = new Myclass();
$obj->{$method_name}();

You have to use callback function call_user_func. To do this You need to make an array:

  • The 1st element is the object
  • 2nd is the method

    call_user_func(array($player, 'doIt'));

You can also do it without call_user_func:

$player->{'SayHi'}();

Or:

$method = 'doIt';
$player->$method();