Passing variables to anonymous PHP functions

Josh Sherman
1 min read
Software Development PHP

The other day I ran into a situation (first time, it seems) where I needed to access a variable inside of an anonymous function inside of preg_replace_callback(). My first thought, even though it went against my better judgement was to simply define the variables as global inside of the function. No dice.

After some research, I found that you need to use the use language construct to be able to access the variables. The syntax is very straight forward:

$callback = function() use ($var1, $var2)
{
	echo 'Yay! I have access to ' . $var1 . ' and ' . $var2 . '!!';
};

Easy peasy! I’m still pretty shocked that I only recently ran into this. Have you learned anything recently that surprised you? Comment below!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles