PHP is great in how it allows you to send a variable-length argument list to a function by using the func_* functions. However, unfortunately (and this has been brought up numerous time in PHP bug reports/feature requests), it doesn't support passing arguments by reference which would have greatly simplified processing multiple variables at once by simply doing: somefunction($a, $b, $c) and having them processed, without having to do any additional assignment.
However, I've discovered a way to leverage several features of PHP and created a very good example that shows how you can process multiple variables in one fell swoop!
The usage is (with my example function/class):
"list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);"
If PHP had ACTUALLY been capable of passing variables by reference when using variable-length argument lists, that could have been reduced to:
"TextEscape::escape_multi($a, $b, $c, $d, $e);"
It's extremely close though, both in simplicity and speed. Just be VERY sure to ALWAYS have the SAME NUMBER AND ORDER of arguments on both sides of that statement.
The use of a static class was just to make the code cleaner and easier to look at. This can be applied to any functions!
Now, onto the code, enjoy the sheer brilliance and enjoy modifying multiple variables at once in just ONE statement! ;-)
<?php
class TextEscape
{
public static function escape_string($sString)
{
return htmlspecialchars($sString);
}
public static function escape_multi()
{
$aVariables = func_get_args();
foreach ($aVariables as $iKey => $sValue)
{
$aVariables[$iKey] = TextEscape::escape_string($sValue);
}
return $aVariables;
}
}
$a = "A<bar";
$b = "B>bar";
$c = "C<bar";
$d = "D>bar";
$e = "E<bar";
print_r(array($a, $b, $c, $d, $e));
list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);
print_r(array($a, $b, $c, $d, $e));
?>
That's the CLEAN LOOKING version of the code, which illustrates exactly what is HAPPENING.
I also made a speedfreak edition of the function, but didn't want to post it as the main example since it's harder to read.
But it's faster, much faster! It passes by reference where it can and loops in a more efficient way.
Just replace the above function with this one, the outcome is the same but the speed is better:
<?php
class TextEscape
{
public static function escape_string(&$sString) {
$sString = htmlspecialchars($sString);
}
public static function escape_multi()
{
$aVariables = func_get_args();
for ($i=(count($aVariables)-1); $i>=0; $i--) {
TextEscape::escape_string($aVariables[$i]); }
return $aVariables;
}
}
?>
Enjoy!