Sian 发表于 2015-12-28 15:03:44

PHP函数中回调函数示例解析

<?php
        // 变量函数:将变量加括号即为以该变量为名称的函数
        // 回调函数:以函数名为变量传入另一个函数做为变量调用,即为回调函数
        function demo($num, $n){
                for ($i = 0; $i < $num; $i++){
                        // 如果$n = "test";
                        // $n()相当于test();
                        // $n($i)相当于函数test($i)
                        if ($n($i)) continue;
                        echo $i.'<br/>';
                }
        }
       
        // 过滤以5结尾的数字
        function test($i){
                if ($i % 5 == 0) return true;
                return false;
        }
       
        // 过滤带3的数字
        function test1($i){
                // 正则表达式 preg_match(string $pattern, string subject)
                if (preg_match('/3/', $i)) return true;
                else return false;
        }
       
        // 过滤回旋数
        function test2($i){
                if ($i == strrev($i)) return true;
                else return false;
        }
       
       
        demo(40, "test");
        demo(40, "test1");
        demo(40, "test2");
页: [1]
查看完整版本: PHP函数中回调函数示例解析