PHP 中的全局变量不起作用

Iva*_*del 1 php variables scope global-variables

我需要$layers从函数内部访问isOk($layer),但是我尝试外部函数变量的一切都$layers可以,但是在函数内部,即使使用 global 也是返回 null。

这是代码:

$layers = array();
foreach($pcb['PcbFile'] as $file){
    if(!empty($file['layer'])){
        $layers[$file['layer']] = 'ok';
    }
}
// Prints OK!
var_dump($layers);

function isOk($layer){
    global $layers;
// Not OK! prints NULL
    var_dump($layers);
    if(array_key_exists($layer, $layers))
        return ' ok';
    return '';
}
// NOT OK
echo isOk('MD');
Run Code Online (Sandbox Code Playgroud)

我总是使用面向对象,但这是一个非常简单的东西,我用一个简单的函数制作......为什么$layers在函数内部没有被正确地“接收”?

cHa*_*Hao 6

看这个...

HalfAssedFramework.php

<?php
class HalfAssedFramework {
    public static function run($path) {
        include $path;
    }
}

HalfAssedFramework::run('example.php');
Run Code Online (Sandbox Code Playgroud)

例子.php

<?php

$layers = array();
foreach($pcb['PcbFile'] as $file){
    if(!empty($file['layer'])){
        $layers[$file['layer']] = 'ok';
    }
}
// Prints OK!
var_dump($layers);

function isOk($layer){
    global $layers;
// Not OK! prints NULL
    var_dump($layers);
    if(array_key_exists($layer, $layers))
        return ' ok';
    return '';
}
// NOT OK
echo isOk('MD');
Run Code Online (Sandbox Code Playgroud)

example.php直接运行,它应该可以工作。运行HalfAssedFramework.php,它不会。

问题是范围。当example.php被包含在run函数内部时,它内部的所有代码都继承了该函数的作用域。在该范围内,$layers默认情况下不是全局的。

要解决此问题,您有几个选择:

  • 如果你知道example.php永远不会直接运行,你可以global $layers;在文件的开头说。不过,如果直接运行脚本,我不确定这是否有效。
  • 更换$layers$GLOBALS['layers']无处不在。
  • $layers作为参数添加到isOk.
  • 按照Geoffrey 的建议,将此代码放在一个类中。