php convert string to method call
<?php开发者_StackOverflow社区
$str = "getList";
//now by doing something to $str i need to call getList() method any sugesstions
function getList(){
echo "get list called";
}
?>
Use the call_user_func() function to call the function by name.
This feature is known as Variable functions
, here is an example from php.net:
<?php
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
More Info:
- http://php.net/manual/en/functions.variable-functions.php
You can use the variable as a function name. This will execute getList()
:
$str();
However, stuff like this is mostly a symptom of a design problem. Care to elaborate what you need this for?
精彩评论