简体   繁体   English

为什么在Drupal块中定义的函数不能访问全局变量?

[英]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. 场景:我已经在PHP 5.2.14下的Drupal 6.20中定义了一个自定义块。 I've enabled PHP Code and I'm attempting to do something like this: 我启用了PHP代码,并尝试执行以下操作:

<?php
  $a = "success";

  function test() {
    global $a;

    print $a;
  }

  test();
?>

It prints nothing on my system, because I cannot seem to scope variable $a. 它在我的系统上不输出任何内容,因为我似乎无法对变量$ a进行范围限定。 I've also tried $GLOBALS['a'] to no avail. 我也试过$ GLOBALS ['a']无济于事。 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. 顺便说一句,在外部作用域中使用global关键字将很高兴使drupal的globals可用。

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. 我对Drupal不太熟悉,但是我猜想这些块包含在某个地方的其他函数/方法中,因此您正在有效地处理嵌套函数,包括在该外部函数的本地范围内。

With that, it makes sense that $a = "success" can't be addressed from within the test() function. 这样,就不能在test()函数中解决$a = "success"问题。

If I'm right, it should work if you slap the global keyword on both scopes. 如果我是对的,那么在两个作用域上使用global关键字就可以了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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