[英]What is the scope of global PHP variables in a Drupal page?
Consider this PHP script: 考虑以下PHP脚本:
<?php
$a = "ok";
function foo() {
global $a; print "[$a]";
}
foo();
?>
It prints [ok]
when run with a PHP interpreter as one would expect. 使用PHP解释器运行时,它会按预期输出
[ok]
。 But it prints just []
if run in a Drupal page. 但是,如果在Drupal页面中运行,它只会打印
[]
。 To make it work in Drupal I have to add another global specification before the variable declaration thus: 为了使其在Drupal中工作,我必须在变量声明之前添加另一个全局规范,因此:
<?php
global $a; // WHY IS THIS NEEDED IN DRUPAL?
$a = "ok";
function foo() {
global $a; print "[$a]";
}
foo();
?>
Likely because Drupal includes the file inside a function: 可能是因为Drupal在函数中包含了文件:
function render() {
include 'my_script.php';
}
That makes $a
local to the function, not global
. 这使得
$a
在函数中$a
局部的,而不是global
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.