Skip to main content
Home
Drupal life hacks

Main navigation

  • Drupal
  • React
  • WP
  • Contact
  • About
User account menu
  • Log in

Breadcrumb

  1. Home

Choosing Between PHP's call_user_func_array and \Closure::fromCallable

By admin, 20 May, 2024

call_user_func_array and \Closure::fromCallable are two different ways to call functions or closures in PHP, each with its own features and applications.

call_user_func_array:

call_user_func_array is a built-in PHP function that invokes a function passed as a string or as an array (containing an object reference and method name) and passes arguments as an array.

Example usage:


function myFunction($arg1, $arg2) {
   return $arg1 + $arg2;
}
$args = [2, 3];
$result = call_user_func_array('myFunction', $args);
echo $result; // Outputs: 5

\Closure::fromCallable:

\Closure::fromCallable is a method available in the Closure class, which creates a closure from a callable object. It takes a string containing the name of a function or method as an argument and returns the corresponding closure. This is particularly useful for creating closures from string function or method names, enabling more dynamic function calls.

Example usage:


$myFunction = function($arg1, $arg2) {
   return $arg1 + $arg2;
};
$callable = \Closure::fromCallable($myFunction);
$args = [2, 3];
$result = $callable(...$args);
echo $result; // Outputs: 5

Differences and Application:

- call_user_func_array is useful when you know the function name beforehand and want to call it with arguments available as an array.
- \Closure::fromCallable is convenient when you want to dynamically create a closure from a string with the name of a function or method, which can be useful when working with frameworks or systems that use strings to define functions or methods, such as Drupal.

In the context of WordPress and Drupal:

- In WordPress, you often use call_user_func_array, especially when working with hooks where the function name is specified as a string.
- In Drupal, \Closure::fromCallable may be more preferable, especially when working with dynamically called hooks or other functions, for example, inside classes where hook methods may be defined dynamically.

Tags

  • #Drupal Planet
  • WordPress

Comments

About text formats

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
Powered by Drupal