Search code examples
phpfunctionmacrostemporary

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


Solution

  • If you have PHP 5.3, enter anonymous functions:

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

    In this case, $prc only lives in the scope of your prepare_param() function.