-1

Within a Drupal module callback function, there is a simple custom function that intakes an array.

The custom function executes correctly when I define the input array within the Drupal module callback function. However, when I define the input array at the root level (global), the custom function within the Drupal module callback function fails.

As a test, I made the custom function simply output the contents of the input array as a string. The first method outputs correctly while the second method does not have any output. Ideally, I'd like to define the array at the global level so that it can be used by other functions.

Thoughts?

<?php

// ** Placement of array for method 2
$mapping = array(
    0 => "name",
    1 => "match"
);

function mymodule_menu() {
    $items = array();

    $items['mymodule'] = array(
        'title' => 'MyModule',
        'page callback' => 'myModule_main',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM
    );

    return $items;
}

function myModule_main() {

    // ** Placement of array for method 1
    $mapping = array(
        0 => "name",
        1 => "match"
    );

    $output = myFunction($mapping);

    echo $output; // ** Returned to client side via AJAX
}
kaspnord
  • 1,403
  • 2
  • 18
  • 28

2 Answers2

5

You need to "import" the global variable into the function's scope using the global keyword.

See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.global

function myModule_main() {
    global $mapping;
    ...
}
mcrumley
  • 5,682
  • 3
  • 25
  • 33
  • 1
    Or use $GLOBALS['mapping'] instead. This method doesn't import the variable into the current scope, just uses it directly. That's good if you won't be using the variable many times. – Diego Agulló Feb 14 '12 at 18:26
  • @DiegoAgulló Thanks for pointing me the right direction guys. The actual working solution is a combination of both your responses. I've updated by question to include the solution (since I don't have enough rep to self-answer my question at the moment). – kaspnord Feb 14 '12 at 18:46
  • Good to hear that! It could be improved, though. Have you tried to avoid using `global` in that context? Is safe to remove it, as the variable is already created in the global scope. – Diego Agulló Feb 14 '12 at 21:14
  • @DiegoAgulló Unfortunately, that doesn't work for me. For my array to be detected, I need to define it as global at the root level. Then, I can access it within the function using GLOBALS. – kaspnord Feb 15 '12 at 15:29
1
<?php

global $foobar;
$foobar = "text";

function myFunction() {
    echo $GLOBALS["foobar"]; // Returns "text"
}

?>
Charles
  • 50,943
  • 13
  • 104
  • 142
kaspnord
  • 1,403
  • 2
  • 18
  • 28