简体   繁体   中英

Why can't functions defined in Drupal blocks access globals?

Scenario: I've defined a custom block in Drupal 6.20 under PHP 5.2.14. I've enabled PHP Code and I'm attempting to do something like this:

<?php
  $a = "success";

  function test() {
    global $a;

    print $a;
  }

  test();
?>

It prints nothing on my system, because I cannot seem to scope variable $a. I've also tried $GLOBALS['a'] to no avail. What gives? I feel like I'm going crazy.

Incidentally, using the global keyword in the outer scope will happily make drupal's globals available.

I'm not hugely familiar with Drupal but I'm guessing that the blocks are included inside some other function/method somewhere, so you're effectively dealing with a nested function, the include being in that outer function's local scope.

With that, it makes sense that $a = "success" can't be addressed from within the test() function.

If I'm right, it should work if you slap the global keyword on both scopes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM