5
function menufun_menu() {
  $items['menufun/%/bar/baz'] = array(
    'title' => 'Hi',
    'page callback' => 'menufun_hello',
    'page arguments' => array(1), // The matched wildcard.
    'access callback' => TRUE,
  );

  return $items;
}

/**
* Page callback.
*/
function menufun_hello($a = NULL, $b = NULL) {
  return t('Hello. $a is @a and $b is @b', array('@a' => $a, '@b' => $b));
}

In the menufun_menu() function, the page argument for the menufun_hello callback is only one. Why does menufun_hello() have two parameters?

2 Answers 2

7

Menu callbacks are passed first the arguments defined in page arguments then excess arguments from the url.

So in the above example:

menufun/1/bar/baz

Will provide these vars:

$a = 1;
$b = NULL;

If you however provide an extra argument in the url:

menufun/1/bar/baz/2

You will transfer it to the menu callback:

$a = 1;
$b = 2;

The other advantedge is like tim writes, that it allows reuse of the same code for various cases, making the module more maintainable.

3
  • in this url menufun/1/bar/baz/2, why it transfer 2 to the $b?
    – enjoylife
    Mar 30, 2011 at 15:41
  • 1
    @enjoylife because it's the first non required argument. If baz was left out, the url wouldn't match, so it's not included, unless included under 'page arguments'
    – googletorp
    Mar 30, 2011 at 17:03
  • You can have an unlimited number of arguments after the required ones - eg menufun/1/bar/baz/2/arg3/arg4 will pass 4 arguments to your page callback - 1, 2, arg3, and arg4.
    – cam8001
    Mar 31, 2011 at 9:16
1

In this case, menufun_hello() takes up to two arguments, but as little as zero, since it provides defaults. This means that menufun_menu() could later pass another argument, and the function signature wouldn't have to change.

1
  • 1
    The function will always be called with at least one argument, because that is required in the menu definition. So the = NULL part is unecessary (unless that function is re-used in another menu definition for example)
    – Berdir
    Mar 30, 2011 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.