开发者

Variable scope in a required file

开发者 https://www.devze.com 2023-02-21 23:09 出处:网络
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

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.


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


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?

Definitely not.

There are NO scope issues regarding includes.
The only scope-dependent issue is user-defined functions.

So, if there are no functions involved, the only cause can be some mistake/mistype - you're editing/including wrong file, or including HTML code it via http or something of the kind. Just double-check.


So my ajax.php file also require_once build.php and config.php

My build.php file require_once no_direct.php as well.

As the function suggests, it will only require no_direct.php ONCE!

So the NULL that I was seeing was coming from build.php's include and not the delete.php's include of no_delete.

0

精彩评论

暂无评论...
验证码 换一张
取 消