在PHP中使用函数名中的"变量"

l2a*_*lba -1 php variables function

可以在函数名中使用变量吗?(如果"是",那怎么样?)

$name = "john";
  function name_function() {
    //Do something
  }
Run Code Online (Sandbox Code Playgroud)

所以我的函数名称将是 john_function()

你明白我的意思吗 ?

如果我有很多功能,我会做得更好,我会说得很清楚

john_init() john_setup() john_save() john_clear()

MrC*_*ode 6

它不能像你想要的那样完成,这似乎就像是

function $name_something(){  }
Run Code Online (Sandbox Code Playgroud)

但您可以使用这样的变量函数:

function john_something()
{
    echo 'called';
}

$name = 'john';

$functionName = $name . '_something';

$functionName();
Run Code Online (Sandbox Code Playgroud)

虽然不是这样,但几乎总有一种更好的方法.


Ari*_*aan 5

eval()是一种方式,我个人认为这很恶心。

如果将代码包含在类中,则可以使用:

class MyCode {
  public static function __callStatic($functionName, $values)
  {
    // $functionName Receive the name of the function
    // $values       Receives an array with all the parameters
    /* Your code per person here */
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式调用此函数:

MyCode::johnDoesSomething('At home', 'playing with PHP');
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅:http ://www.php.net/manual/en/language.oop5.overloading.php#object.call