Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope loss in included files in php

Tags:

scope

include

php

There are a few posts relevant to this but I'm not seeing anything near to the situation I'm struggling with.

I've inherited a rather large codebase which the original designer has taken some interesting methods of design. I'm attempting to call a method of a class that's defined. The class file itself has some global variables set. I call this method from a function, where also, I've included this file. When the method runs, the global variables are no longer defined. See below:

My File:

<?php //myScript.php

echo("Calling foo(): ");
foo();

function foo() {
   include '../../php/class.bar.php';
   $bar = new bar();
   $bar->doSomething();
}
?>

../../php/class.bar.php:

$GLOBAL_ARRAY_ONE[0] = 'Here I am';
$GLOBAL_ARRAY_ONE[1] = 'JT';

class bar {
   public $itsFoo = array();
   public $itsBar = array();

   public function doSomething() {
      global $GLOBAL_ARRAY_ONE;
      $this->itsFoo[0] = $GLOBAL_ARRAY_ONE[0];
      $this->itsFoo[1] = $GLOBAL_ARRAY_ONE[1];

      var_dump($this->itsFoo);
   }
}

So, when I run "myScript.php" The output is: calling foo(): NULL

I personally wouldn't declare global arrays in a script like that but, I see no reason why I shouldn't have access to them.

Any ideas? Thanks!

like image 490
eggmatters Avatar asked Feb 02 '26 01:02

eggmatters


1 Answers

Since you include the file inside a function - GLOBALS cannot be defined there (neither a class). What you probably want to do is to include class.bar.php outside (of foo()):

<?php //myScript.php

include '../../php/class.bar.php';

echo("Calling foo(): ");
foo();

function foo() {   
   $bar = new bar();
   $bar->doSomething();
}
?>
like image 123
Nir Alfasi Avatar answered Feb 04 '26 14:02

Nir Alfasi