PHP Function Call_User_Func_Array
PHP is famous for its flexibility. The object-oriented model enables developers to extend code through inheritance, encapsulate functions in reusable objects, and generally make things work the way they want to for their application. However, there is another approach that provides even more flexibility: functional programming. In this article, we’ll take a look at an in-built PHP function, call_user_func_array, that can help you get your codebase up and running fast.
This function takes a callback (which is usually called as a lambda) and an array of parameters to pass to that lambda. It then assigns each parameter to the lambda’s parameter list, one at a time. The result is a function that can handle any number and type of arguments, without having to use a switch statement.
The key to this function is that it passes arguments by value, rather than by reference. This may seem like a small difference, but it can have a big impact. In the PHP world, passing parameters by reference usually results in a warning and having the function return false. However, when calling a user function with call_user_func_array, passing by value is allowed, and the function will return true.
While it does not work on things like __invoke methods, this functionality is very useful for functions that accept a variable number of parameters, such as constructors. And because it works on both callables and lambdas, you can have a flexible codebase that’s ready for anything.