TIL*ยน you can import just a function in a .php file, like we do with classes. It works from PHP 5.6+, so there’s no weird compatibility issue. And it’s dead simple.
Here’s an example from Safe PHP, specifically let’s say we want to use the safer*ยฒ version of json_decode. Pay attention at how this allows us to override PHP’s default json_decode global function:
// First we import it
use function Safe\json_decode;
// And then we just use it
$foobar = json_decode($content);
Yes, it’s not a jode. That’s all. You tell PHP that what you’re importing is a function and the just use the function’s name instead of a class name. After that, you can use said function in you code as if it were a global or local function. How cool is that?!
- *1 Not really today, this post was in draft state since 2017/12/22 o.o
-
*2 These are a set of core PHP functions rewritten to throw exceptions instead of returning
falsewhen an error is encountered. For more information about this project you can go to their repo https://github.com/thecodingmachine/safe
Leave a Reply