在 PHP 中从字符串调用函数

PHP 有一个内置函数,如 call_user_func() 从字符串调用函数或将其存储在旧版本的变量中。PHP 还可以将函数存储到变量中,并在需要时使用它。

本教程演示了从存储在变量中的字符串调用函数的不同方法。

使用 call_user_func() 从 PHP 中的字符串调用函数

PHP 内置函数 call_user_func() 可用于此目的。

例子:

<?php
function demo_func($name) {
    echo "Hello This is Delftstack employee ".$name;
}
$demo_array = array ("John", "Shawn", "Michelle", "Tina");
foreach ($demo_array as $name) {
    call_user_func('demo_func', $name);
    echo "<br>";
}
?>

上面的代码使用参数名称调用函数 demo_func

输出:

Hello This is Delftstack employee John
Hello This is Delftstack employee Shawn
Hello This is Delftstack employee Michelle
Hello This is Delftstack employee Tina

使用变量方法从 PHP 中存储在变量中的字符串调用函数

在 PHP 中,我们还可以将函数存储在变量中。函数名应该以字符串的形式赋给变量,然后我们就可以称函数为变量了。

例子:

<?php
function demo_func1($name) {
    echo "Hello This is Delftstack employee ".$name;
}
$demo_function = 'demo_func1';
$demo_array = array ("John", "Shawn", "Michelle", "Tina");
foreach ($demo_array as $name) {
    $demo_function($name);
    echo "<br>";
}
?>

其输出也将类似于我们上面的第一个示例。

Hello This is Delftstack employee John
Hello This is Delftstack employee Shawn
Hello This is Delftstack employee Michelle
Hello This is Delftstack employee Tina

call_user_func 是老方法。我们可以直接将函数作为字符串存储到变量中,通过调用变量来调用函数。