0
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ I think KISS (Keep It Simple and Stupid). \$\endgroup\$ – Shaun Bebbers Nov 8 '17 at 13:28
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\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 Nov 8 '17 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 Nov 8 '17 at 13:48
  • \$\begingroup\$ Ah thanks I did not realize that the § sign is not a char within the standard american keyboard. \$\endgroup\$ – Blackbam Nov 8 '17 at 19:42
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.