PHP how to use values from outside an anonymous function

In php you can create an anonymous function as a parameter to any other function that requires a function as the input. But you run into a small problem pretty quickly. When you create an anonymous function in PHP it has no access to variables outside of it’s curly braces. So what do you do if your anonymous function needs values from outside?

Meet use

You simply use the use keyword like this.

$columnsToSearch = array($columnToSearch);
$searchSql = SqlQueryBuilder::buildMatchesInTextSearchQuery($text, $columnsToSearch, $searchMode);
$dbConn = $this->mysql->getDbConnection();
$st = $dbConn->prepare($searchSql);
//$this->doPDOBindCalls($st, $whereColumns);
$st->execute();
$result = $st->fetchAll();
$st->closeCursor();
$this->mysql->closeDbConnection();
$values = array();
if(is_array($result)){
    $values = array_map(function ($value) use ($columnToSearch){
        return $value[$columnToSearch];
    },$result);
}

The above code searches a database gets all the values then uses array_map to flatten the result into one array of values Notice the anonymous function to array_map and the use statement. You can separate the values after use with a comma to include multiple variables.


Posted

in

by

Tags:

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d