Page 1 of 1

variable scoped in requiring file but not in required file

Posted: Tue Jun 23, 2009 1:34 pm
by tepez
Hi,

I'm working on a project consisting of several php files.

The settings are similar to:

Code: Select all

//main.php - this file is loaded first
require_once 'act.php';

Code: Select all

//act.php
require_once 'lib.php';
 
$gVar; // $gVar is scoped here
$obj = new Obj();
$obj->foo(); 

Code: Select all

//lib.php
require_once 'globals.php';
 
class Obj {
  foo() 
  { 
    global $gVar;
    echo "$gVar"; // $gVar is not scoped here
  }
} 

Code: Select all

//globals.php
$gVar = 0;
The problem is $gVar is available (in scope) on act.php but when I'm calling Obj::foo, $gVar its not available, altough I use global and altough act.php knows globals.php through lib.php.

The problem doesn't exist in this example, but it does in my project, so I geuss have some king of bug.
What might be the reason for a variable to be scoped in including file (act.php) but not in included file (lib.php)?

Re: variable scoped in requiring file but not in required file

Posted: Tue Jun 23, 2009 2:01 pm
by Darhazer
If you include files in a function (as far as I remember Joomla do, or it was some other open-source CMS that I was debugging once), than you are declaring the variable in the function's scope, not in the global one.

If not, and if the example code works, and you are not showing the code that does not, it will be hard thing to debug :mrgreen:

Re: variable scoped in requiring file but not in required file

Posted: Tue Jun 23, 2009 2:12 pm
by tepez
thanks!! it seems to be the reason.

Is there any way to include a file from a function, but apply the variables declarations on the global scope.

In the content of the example below, I want $gGlobal to be available at B::foo

Code: Select all

<?php
    // a.php
    
    function fooA() {
        require_once 'b.php'; 
        
        $b = new B();
        $b->foo();  
    }
    
    fooA();
?>

Code: Select all

<?php
    // b.php
  require_once 'c.php';
  
  class B {
      
      function foo()
      {
        global $gGlobal;   // how can I make $gGlobal available here
        echo "B::foo " , $gGlobal , "\n";
      }
    
  }
?>

Code: Select all

<?php
  //c.php
  $gGlobal = 1;
?>

Re: variable scoped in requiring file but not in required file

Posted: Tue Jun 23, 2009 2:40 pm
by Christopher
The problem is that in you example it should be:

Code: Select all

//lib.php
require_once 'act.php';        // NOT 'globals.php'

Re: variable scoped in requiring file but not in required file

Posted: Fri Jun 26, 2009 1:02 am
by Darhazer
tepez
My solution was to work with (super)global variables, i.e. instead of having:

Code: Select all

$gGlobal = 1;

Code: Select all

$GLOBALS['gGlobal'] = 1;