php:如何同时清理许多变量?

时间:2015-10-29 21:10:12

标签: php

这是我的php函数:

function test($a,$b,$c) {
 sanitize($a,$b,$c);
 echo "$a $b $c";
}

function test2($m,$n) {
 sanitize($m,$n);
 echo "$m $n";
}

function sanitize() {
 // escape strings with stripslashes (and other filters later)
}

test2("he'llo", "wo'rld");
test("he'llo", "wo'rld","hap'y");

是否可以保持test和test2功能?

我只想避免有3行:

$a=sanitize($a); 
$b=sanitize($b);
$c=sanitize($c);

并且刚刚:

sanitize($a, $b, $c);

3 个答案:

答案 0 :(得分:4)

Php 5.6 +

function sanitize( &...$args){
    foreach($args as &$arg){
        //your sanitising code here, eg:
       $arg = strtolower($arg);
    }
}

答案 1 :(得分:3)

func_get_args将函数的所有参数作为数组返回。 array_map将函数应用于数组的所有成员。

<?php
function test() {
    $arguments = func_get_args();
    $cleaned = array_map('sanitize', $arguments);
    echo implode(" ", $cleaned);
}

// one liner, for those who like such things!
function test2() {echo implode(" ", array_map('sanitize', func_get_args()));}
?>

顺便说一句,从函数回显不是好形式。您应该返回该值...

答案 2 :(得分:2)

如果您没有PHP 5.6 +

function sanitize(&$p1, &$p2 = null, &$p3 = null, &$p4 = null, &$p5 = null, &$p6 = null, &$p7 = null, &$p8 = null, &$p9 = null, &$p10 = null, &$p11 = null, &$p12 = null, &$p13 = null, &$p14 = null, &$p15 = null, &$p16 = null, &$p17 = null, &$p18 = null, &$p19 = null, &$p20 = null, &$p21 = null, &$p22 = null, &$p23 = null, &$p24 = null, &$p25 = null) {
    $argc = func_num_args();
    for ($i = 1; $i <= $argc; $i++) {
        _sanitize(${"p$i"});
    }
}
function _sanitize(&$a) {
    $a = addslashes($a); // and other filters
}

test2("he'llo", "wo'rld");
test("he'llo", "wo'rld","hap'y");

使用脚本,如果需要,可以生成超过25个参数(或手动构建: - ))

然后,当您迁移到PHP 5.6时,您可以使用Steve's answer仅触及定义而不是其余代码。