在 PHP 中從字串呼叫函式

Sheeraz Gul 2023年1月30日
  1. 使用 call_user_func() 從 PHP 中的字串呼叫函式
  2. 使用變數方法從 PHP 中儲存在變數中的字串呼叫函式
在 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 是老方法。我們可以直接將函式作為字串儲存到變數中,通過呼叫變數來呼叫函式。

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - PHP Function