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!





Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: