PHP 中實現回撥函式 (php callback function)
PHP 中實現回撥函式 (php callback function)
資料來源: https://www.delftstack.com/zh-tw/howto/php/implement-a-callback-in-php/
方案01. PHP 中建立一個 callback 函式並使用 call_user_func 執行
<?php function testFunction() { echo "Testing Callback \n"; } // Standard callback call_user_func('testFunction'); ?>
方案02. PHP 中建立一個 callback 函式並使用 array_map 方法執行
<?php function length_callback($item) { return strlen($item); } $strings = ["Kevin Amayi", "Programmer", "Nairobi", "Data Science"]; $lengths = array_map("length_callback", $strings); print_r($lengths); ?>
方案03. PHP 中實現多個回撥函式並使用使用者定義的函式執行它們
<?php function name($str) { return $str . " Kevin"; } function age($str) { return $str . " Kevin 23 "; } function testCallBacks($str, $format) { // Calling the $format callback function echo $format($str)."<br>"; } // Pass "name" and "age" as callback functions to testCallBacks() testCallBacks(" Hello", "name"); testCallBacks(" Hello", "age"); ?>
方案04. PHP 中使用 static 類和 call_user_func 將 static 方法實現為 callback 函式
<?php // Sample Person class class Person { static function walking() { echo "I am moving my feet <br>"; } } //child class extends the parent Person class class Student extends Person { static function walking() { echo "student is moving his/her feet <br>"; } } // Parent class Static method callbacks call_user_func(array('Person', 'walking')); call_user_func('Person::walking'); // Child class Static method callback call_user_func(array('Student', 'Student::walking')); ?>
One thought on “PHP 中實現回撥函式 (php callback function)”
C/C++ callback function 函數指標 類似