This is the function:
/**
* Apply 1..n one parameter functions to the given variable.
*
* @param array/mixed $callback: An array of Callback functions which accept one parameter.
* @param $var: The variable to apply them to.
*/
function §($callback,&$var) {
if(is_array($callback)) {
foreach($callback as $c) {
$var = $c($var);
}
} else {
$var = $callback($var);
}
}
$a = "4";
§('intval',$a);
var_dump($a);
§(['intval','exp','ceil'],$a);
var_dump($a);
Result:
int(4)
float(55)
What do you think? This functions saves typing a lot of assignments, but could it confuse users?
-
\$\begingroup\$ I think KISS (Keep It Simple and Stupid). \$\endgroup\$Shaun Bebbers– Shaun Bebbers2017年11月08日 13:28:25 +00:00Commented Nov 8, 2017 at 13:28
2 Answers 2
I like it, though it looks a lot like array_map()
. I would get rid of the §
symbol. Instead, 'use' a very short custom function alias that is ASCII. Something like map()
.
Also, you could make this more powerful if you use variadics.
-
\$\begingroup\$ Sure, variadics should be added. Whats bad about the §-symbol is it used for anything? Or do you just think its bad to use a non alphanumeric character in function name? \$\endgroup\$Blackbam– Blackbam2017年11月08日 13:45:10 +00:00Commented Nov 8, 2017 at 13:45
-
\$\begingroup\$ Nothing wrong with that character and if you like, then go for it. I don't mind it so much myself, I like your creativity. However, it's been my experience that functions that are not easy to type are not well received by others. So if you want others to love this, name it something on their keyboard. \$\endgroup\$jaswrks– jaswrks2017年11月08日 13:48:24 +00:00Commented Nov 8, 2017 at 13:48
-
\$\begingroup\$ Ah thanks I did not realize that the § sign is not a char within the standard american keyboard. \$\endgroup\$Blackbam– Blackbam2017年11月08日 19:42:50 +00:00Commented Nov 8, 2017 at 19:42
Beside the answer of jaswrks, i have a few remarks:
You are never actually checking, if $callable
is actually callable. It may depend where you actually use the function, but i can imagine that somewhere this may cause some hard to track bugs.
It might also be a good idea to always create an Array
from your input so your function looks like this:
function §($callback,&$var) {
$callback = !is_array($callback) ? [$callback] : $callback;
foreach($callback as $c) {
$var = $c($var);
}
}
Now you have a single line where your actual call happens. This might be handy if you want to add some checks or features.