Passing variables to anonymous PHP functions

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!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.