Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope in a required file

Tags:

scope

php

I'm calling a file named ajax.php (from my browser for testing)

ajax.php require_once delete.php

delete.php require_once no_direct.php

delete.php starts like this:

$allowed = array('group'=>'admin');
require_once(ASSETS.'/no_direct.php'); //Yes, ASSETS is defined and no_direct is being included.

In no_direct.php I'm trying to:

var_dump($allowed)

and I just keep coming up NULL.

Does this happen because we are running inside ajax.php's require_once function and the scope of $allowed pushes back to the GLOBAL scope not allowing me to access it from no_delete.php?

I was looking here: PHP variable defined in 'parent' file not recognized in 'required' file , just to be diligent.

I'm sure I could solve this with the GLOBAL keyword, but I was hoping for a little clarification. The PHP scope doc didn't seem to answer the question for me.

It wasn't wrapped in another function as thought to be the case.

like image 891
Senica Gonzalez Avatar asked Jun 13 '26 08:06

Senica Gonzalez


1 Answers

Is there any chance that you already have called require_once(ASSETS.'/no_direct.php'); before you assigned value to $allowed?

require_once(ASSETS.'/no_direct.php');
...

$allowed = array('group'=>'admin');
require_once(ASSETS.'/no_direct.php');

Script no_direct.php should not output $allowed in this case.

Output will be:

Notice: Undefined variable: allowed in D:\wampserver\www\gim\no_direct.php on line 2
NULL 

p.s. there's my path on localhost in wamp for my test file

like image 185
Wh1T3h4Ck5 Avatar answered Jun 16 '26 03:06

Wh1T3h4Ck5