0

Scenario:

  1. there is a global array $cache.
  2. there is 1 function, cacheWriter(), that updates $cache with various cachable objects. cacheWriter() runs a switch() with different cases that each update a certain key in $cache.
  3. some cases in cacheWriter() depend on other cases to correctly update $cache. In these cases, the script checks if the array key it depends on already exists in $cache, and if not, it will call cacheWriter() from within to get the case it needs.

In these cases, will $cache already be updated and contain the new content, or only the next time the function runs?

Example:

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()

Obviously, this function is extremely simplified, but it's the basic concept. Thanks!

bobsoap
  • 3,865
  • 6
  • 26
  • 42
  • 2
    PHP is not multithreaded, so if you update a global, that new value is immediately in effect everywhere. – Marc B Feb 03 '12 at 15:59
  • Thanks Marc, that's what I needed to know. Do you want to add this as an answer so that I can accept it? – bobsoap Feb 03 '12 at 16:03
  • 1
    See [globals in php mean something different](http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why) – mario Feb 03 '12 at 16:09

1 Answers1

2

Yes, the value of the global will contain the last write. The global directive is for scoping purposes, to tell the interpreter which variable to use - it doesn't actually "import" the value and hold onto it at that point.

Borealid
  • 86,367
  • 8
  • 101
  • 120