php回调函数的实现方法介绍(代码)

不言
不言 转载
2023-04-04 10:50:01 2627浏览

本篇文章给大家带来的内容是关于php回调函数的实现方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

名称id说明选项options
回调过滤器(callback)1024调用自定义函数来过滤数据callable函数或方法

回调函数实现

回调函数必须接受一个待过滤的值,并返回过滤后的值,回调函数有四种实现方式。

第一种是直接定义回调函数,并在使用过滤器函数时,将回调过滤器的options设置为自定义的回调函数。

<?php
function trimString($value){
    return trim($value);
}
$args=array(
    'options'=>'trimString',
);
var_dump(filter_var('abc ',FILTER_CALLBACK,$args));
?>

第二种是在使用过滤器函数时,将回调过滤器的options直接设置为回调函数。

<?php
$args=array(
    'options'=>function ($value){return trim($value);},
);
var_dump(filter_var('abc ',FILTER_CALLBACK,$args));
?>

第三种是通过闭包实现调用回调函数来传递其他参数。

<?php
function trimString($array){
    return function($value = null) use ($array){
        if(key_exists('character_mask',$array)){
            return trim($value,$array['character_mask']);  
        }
        return trim($value);
    };
}
$args=array(
    'options'=>trimString(array("character_mask"=>'a..c ')),
);
var_dump(filter_var('abcd ',FILTER_CALLBACK,$args));
?>

第四种是使用类中的函数作为回调函数,可以用来将多个过滤器回调函数集中到一起。

<?php
class TrimFilter{
    private $options=array();
    private $defaults=array('character_mask'=>" \t\n\r\0\x0B");
    public function __construct(array $options=array()){
        $this->options = $options;
    }
    
    private function get_options(array $defaults){
        return array_merge($defaults, $this->options);
    }
    
    function trimString($value){
        $ops=$this->get_options($this->defaults);
        if(key_exists('character_mask',$ops)){
            return trim($value,$ops['character_mask']);  
        }
        return trim($value);
    }
    
    function ltrimString($value){
        $ops=$this->get_options($this->defaults);
        if(key_exists('character_mask',$ops)){
            return ltrim($value,$ops['character_mask']);  
        }
        return ltrim($value);
    }
    
    function rtrimString($value){
        $ops=$this->get_options($this->defaults);
        if(key_exists('character_mask',$ops)){
            return rtrim($value,$ops['character_mask']);  
        }
         return rtrim($value);
    }
    
}

$trim_args=array(
    'options'=>array(
        new TrimFilter(array('character_mask'=>" a")),TRIMSTRING
    )
);
$ltrim_args=array(
    'options'=>array(
        new TrimFilter(array('character_mask'=>" a")),LTRIMSTRING
    )
);
$rtrim_args=array(
    'options'=>array(
        new TrimFilter(),RTRIMSTRING
    )
);
$str="abcd ";
var_dump(filter_var($str,FILTER_CALLBACK,$trim_args));
var_dump(trim($str," a"));
var_dump(filter_var($str,FILTER_CALLBACK,$ltrim_args));
var_dump(ltrim($str," a"));
var_dump(filter_var($str,FILTER_CALLBACK,$rtrim_args));
var_dump(ltrim($str));
?>


以上就是php回调函数的实现方法介绍(代码)的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:CSDN,如有侵犯,请联系admin@php.cn删除