Calling a method with an array value in PHP

I have a class like this

class someclass{
  public function somemethod(){}
}

      

Now I have an array:

$somearray['someclass']  = new someclass();
$somearray['somemethod'] = 'somemethod';

      

How can I run them, I tried the following:

$somearray['someclass']->$somearray['somemethod']();

      

usign this I am getting the following error:

Fatal error: Method name must be a string in ......................

Anyone have an idea how to do this?

+2


a source to share


5 answers


I cannot reproduce the error with the code provided (as @webbiedave pointed out the syntax is correct).

However, you can put the method name on a string before using it to ensure that the method name is a string. This ensures that even it is a user-defined object with a method __toString()

, it will be converted to its string representation.



$somearray['someclass']->{(string)$somearray['somemethod']}();

      

0


a source


If it doesn't want to work this way (and I agree with that), you can try:



call_user_func(array($somearray['someclass'], $somearray['somemethod']));

      

+1


a source


Try $somearray['someclass']->{$somearray['somemethod']}();

0


a source


The following code has been tested and appears to be what you need:

<?php


class someclass{
  public function somemethod(){ echo 'test'; }
}


$somearray['someclass']  = new someclass();
$somearray['somemethod'] = 'somemethod';

$somearray['someclass']->{$somearray['somemethod']}();

?>

      

0


a source


How about this:

foreach (get_class_methods(get_class(new someclass()) as $method) {
    $method();    
}

      

0


a source







All Articles