Can I use the static method as a menu callback in drupal?

When defining the hook_menu element hook_menu I can use the public static method for the class, and not use the naming convention of the global underscore drupal, usually for?

For example, is the following permissible?

 $items['test'] = array( 'page callback' => 'MyClass::test', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK ); 
+6
source share
2 answers

menu_execute_active_handler () , which is a Drupal function that calls the menu callback, contains the following code:

 if ($router_item = menu_get_item($path)) { if ($router_item['access']) { if ($router_item['file']) { require_once($router_item['file']); } return call_user_func_array($router_item['page_callback'], $router_item['page_arguments']); } else { return MENU_ACCESS_DENIED; } } 

In PHP 5.2.3 or later, you can call call_user_func() as call_user_func('MyClass::myCallbackMethod') .

The only problem I see is third-party modules that do not expect the menu callback to be a static class method, and use function_exists($menu_callback) .
Then, as Coder1 reported, if the main Drupal modules or other modules try to call menu_callback using code similar to the following, then they can cause a PHP error.

 $menu_callback = $router_item['page_callback']; $menu_callback($router_item['page_arguments']); 
+2
source

Yes, it should work like it does:

 class Test { static function method() { echo 'Yes'; } } $name = 'Test::method'; call_user_func_array($name, array()); 

But why do you need to do this?

As you said, the usual functions are usually used (which you can easily load if necessary by the menu system) for page callbacks.

If you work with Drupal, you must follow the official coding standard. Even if it is only for custom modules. If someone needs to pick up your work at some point, it will be easier for them if the code complies with the same standard that is used everywhere.

See also http://groups.drupal.org/node/20728#comment-71907

+1
source

Source: https://habr.com/ru/post/886484/


All Articles