Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can temporary functions/macros be created in PHP?

Take a look at the following illustration:

// Trims input, fixes spaces and encodes bad glyphs. Also works with arrays.
function prepare_param($param)
{
    $retval = "";

    function prc($param)
    {
        $r = split(" ", trim($param));
        foreach($r as $i => $e)
            $r[$i] = urlencode($e);
        return join("+", $r);
    }

    // If input is an array
    if(is_array($param))
    {
        $retval = array();

        foreach($param as $e)
            $retval[] = prc($e);
    }
    // If input is a string
    else if(is_string($param))
    {
        return prc($param);
    }
    else throw new Exception("Invalid input! Expected String or Array.");
}

Obviously the function prc will now be declared globally, even though declared inside a function. Is there a way to follow this principle, creating a tiny function/macro inside another function as not to litter the global scope? The alternative would be to make a class with a private function, which seems like overkill for my use.

Any help appreciated

like image 358
Hubro Avatar asked Dec 08 '25 06:12

Hubro


1 Answers

You probably want closures, which are anonymous functions.

like image 139
Marc B Avatar answered Dec 09 '25 18:12

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!