views:

566

answers:

2

I am integrating third party code into the web application I am writing in Zend Framework.

The code I want to integrate declares variables as global. It works on its own, but not when I include it within Zend Framework. Initially I suspected that there is something in Zend Framework that is disabling the declaration of global variables. I have the following test code in a controller:

public function testglobalAction()
{
   $a = 1;
   function b()
   {
      global $a;
      echo $a*2;
   }

   b();
}

When I ran it prints out 0, as opposed to 2. On top of that running the same code on its own in the same web server prints out 2.

I understand that I could replace all the global instances to use Zend Registry. However, a grep showed me that there are roughly 700 lines I have to change, so it is not feasible at the moment.

Does anyone know how I can solve this problem?

+1  A: 

No. Zend Framework doesn't disable globals, as it is not possible. The $GLOBALS array is controlled by the php.ini register_globals directive. It cannot be changed at runtime using ini_set.

See the documentation for reference.

Note: Check your .htaccess files for any per-directory php_value overrides.

hobodave
I did try turning on register_globals and I get the same result. There are no php_value overriding the directive either.It is funny that I have a test file in the same web server that prints out 2 which is the expected result. However, when I run that code in a controller I get 1.
Marcel Tjandraatmadja
+7  A: 

Your original $a variable isn't global.

Any variable declared inside of a method is local to that method, unless it's been previously declared global in the current scope.

Try this

public function testglobalAction()
{
 global $a;
    $a = 1;
    function b()
    {
  global $a;
  echo $a*2;
 }

 b();
}
Alan Storm
Additionally, PHP scoping prevents access to outer local variables within inner functions/calls, despite the fact that those variables are still in active memory and accessible to the application flow once the inner function exits.
eyelidlessness
Almost eyelidlessness. Prior to PHP 5.3, "inner" functions didn't exist. When you define a function inside a method as above, you're actually defining a function in the global scope (if you called testglobalAction you'd get a Fatal error: Cannot redeclare b(). PHP 5.3 introduced real lambda functions and closures, and requires you to specify which variables you want to import from the outer scope.
Alan Storm