Drupal页面中全局PHP变量的范围是什么


What is the scope of global PHP variables in a Drupal page?

考虑一下这个PHP脚本:

<?php
  $a = "ok";
  function foo() {
    global $a; print "[$a]";
  }
  foo();
?>

当使用PHP解释器运行时,它会打印[ok],正如人们所期望的那样。但如果在Drupal页面中运行,它只打印[]。为了让它在Drupal中工作,我必须在变量声明之前添加另一个全局规范:

<?php
  global $a; // WHY IS THIS NEEDED IN DRUPAL?
  $a = "ok";
  function foo() {
    global $a; print "[$a]";
  }
  foo();
?>

可能是因为Drupal在函数中包含文件:

function render() {
    include 'my_script.php';
}

这使得$a是函数的本地,而不是global

相关文章: