0

I have PHP files a bit like this

public_html/environment.php
public_html/task.php
phpbin/actions.php
phpbin/library.php

environment.php is included by public_html/* before any other php files are included, phpbin/* assumes everything in environment.php is already available.

It defines these two globals

$g_foo = "...";
$g_bar = "...";

task.php includes this logic

function do_stuff ()
{
    require_once determine_required_file ();
    ...
}

In this case, determine_required_file() returns "/path/to/phpbin/actions.php"

actions.php in turn contains

require_once "/path/to/phpbin/library.php"

Finally, library.php contains

$x = $g_foo;
$y = $g_bar;

I get this error:

Undefined variable: $g_bar;

Now, $g_foo and $g_bar are strictly read-only except in environment.php, I have exhaustively grepped and verified that there are no other places which create or modify variables with these names.

I am aware that PHP globals are weird, and doing things like including files from within functions can mess up your scope. I know that I should probably use define() or some other method, yeah yeah.

My question is this (yes, I'm asking you to speculate in the absence of full code, sorry):

Why might $g_bar generate an error but not $g_foo?

I assume the in-function-inclusion is probably responsible, but assuming these globals really are read-only, what should I be looking for as the culprit for why one ends up in global scope in library.php but not the other?

spraff
  • 32,570
  • 22
  • 121
  • 229
  • Unless you explicitly use the `global` keyword, *neither* should be accessible inside a function (all your code is executing in a function context). As such, can't reproduce/can't advice. – deceze Apr 19 '16 at 11:01

1 Answers1

0

You need to use include_once instead of required_once for your fields that needed your global variables, or define a global $g_bar, $g_foo.

http://php.net/manual/en/language.variables.scope.php

cmizzi
  • 188
  • 1
  • 14
  • I use require because it fails hard if there is an error. If I switch to include, how can I make it fail hard in the same way? – spraff Apr 19 '16 at 11:06
  • Use `global $g_bar, $g_foo` when you use `required` or `include` in order to tell that those variables need to be used in your file. http://stackoverflow.com/questions/2418473/when-should-i-use-require-once-vs-include. `include` will not failed on non-existing file, `required` does. http://fr.php.net/manual/en/function.include.php I thing `include` is better in your case because of variable scope – cmizzi Apr 19 '16 at 11:27