Is there a way to set the scope of require_once()

2019-04-19 05:22发布

I'm looking for a way to set the scope of require_once() to the global scope, when require_once() is used inside a function. Something like the following code should work:

file `foo.php':

<?php

$foo = 42;

actual code:

<?php

function includeFooFile() {
    require_once("foo.php"); // scope of "foo.php" will be the function scope
}

$foo = 23;

includeFooFile();
echo($foo."\n"); // will print 23, but I want it to print 42.

Is there a way to explicitly set the scope of require_once()? Is there a nice workaround?

7条回答
啃猪蹄的小仙女
2楼-- · 2019-04-19 05:56

You will need to declare global in your foo.php:

<?php
 global $foo;
 $foo = 42;
?>

Otherwise it's probably not possible.

You could try to play around with extract(), get_defined_vars(), global and $GLOBALS in various combinations maybe... like iterating through all defined variables and calling global on them before requiring a file...

$vars = get_defined_vars();
foreach($vars as $varname => $value)
{
  global $$varname; //$$ is no mistake here
}
require...

But i'm not quite sure if you get to where you want to go...

查看更多
登录 后发表回答