Calling a method with an array value in PHP
I have a class like this
class someclass{
public function s开发者_运维百科omemethod(){}
}
Now I have an array:
$somearray['someclass'] = new someclass();
$somearray['somemethod'] = 'somemethod';
How can I fire them, I tried the following:
$somearray['someclass']->$somearray['somemethod']();
usign this I get the following error:
Fatal error: Method name must be a string in ......................
Anyone have an idea on how to do this?
If it doesn't want to work that way (and I agree it should), you could try:
call_user_func(array($somearray['someclass'], $somearray['somemethod']));
I cannot reproduce the error with the code provided (As @webbiedave pointed out the syntax is correct).
However you could cast the method name to a string before using it to ensure the method name is a string. This will ensure that even it is a user defined object with a __toString()
method, it will be converted into its string representation.
$somearray['someclass']->{(string)$somearray['somemethod']}();
Try $somearray['someclass']->{$somearray['somemethod']}();
The following code was tested and seems to be want you want:
<?php
class someclass{
public function somemethod(){ echo 'test'; }
}
$somearray['someclass'] = new someclass();
$somearray['somemethod'] = 'somemethod';
$somearray['someclass']->{$somearray['somemethod']}();
?>
How about this:
foreach (get_class_methods(get_class(new someclass()) as $method) {
$method();
}
精彩评论