全局 PHP 变量是否始终在运行时包含其最新值


Does a global PHP variable always contain its most recent value at runtime?

场景:

  1. 有一个全局数组$cache.
  2. 有 1 个函数,cacheWriter() ,更新$cache各种可缓存的对象。 cacheWriter()运行一个 switch((不同的情况,每个更新$cache中的某个键。
  3. cacheWriter()中的某些情况依赖于其他情况才能正确更新$cache .在这些情况下,脚本会检查数组键是否它依赖于 $cache 中已经存在,如果没有,它将调用 cacheWriter()内部获得所需的案例。

在这些情况下,$cache是否已经更新并包含新内容,还是仅在下次函数运行时

更新?

例:

function cacheWriter($case) {
    global $cache;
    if($cache[$case]) {
        $out = $cache[$case];
    } else {
        switch($case) {
            case 1 : 
                $cache[1] = 'some object';
            break;
            case 2 :
                if(!$cache[1]) {
                    $dummy = cacheWriter(1);
                }
                //QUESTION:
                //will $cache[1] now exist right here (since it's global)
                //so that I can now simply access it like this:
                $cache[2] = $cache[1]->xyz;
                //OR,
                //do I have to use $dummy to get [1]
                //and $cache[1] will only exist the next time the function runs?            
            break;
        }
        $out = $cache[$case];
    }
    return $out;
}//cacheWriter()

显然,这个函数非常简化,但它是基本概念。谢谢!

是的

,全局的值将包含最后一次写入。global指令用于范围目的,告诉解释器使用哪个变量 - 它实际上并没有"导入"值并在那时保留它。