本篇文章给大家带来的内容是关于php回调函数的实现方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
回调函数实现
回调函数必须接受一个待过滤的值,并返回过滤后的值,回调函数有四种实现方式。
第一种是直接定义回调函数,并在使用过滤器函数时,将回调过滤器的options设置为自定义的回调函数。
?phpfunction trimString($html' target='_blank'>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));?
第三种是通过闭包实现调用回调函数来传递其他参数。
?phpfunction 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));?
第四种是使用类中的函数作为回调函数,可以用来将多个过滤器回调函数集中到一起。
?phpclass 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教程
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
新闻热点
疑难解答