开发者

PHP include_once inside a function to have global effect

I have a function in php:

function importSomething(){
    include_once('something.php');
}

How do i make it sot that the include_once has a global effect? That everything imported will开发者_C百科 be included in the global scope?


You can return all the variables in the file like so...

function importSomething(){
   return include_once 'something.php';
}

So long as something.php looks like...

<?php

return array(
    'abc',
    'def'
);

Which you could assign to a global variable...

$global = importSomething();

echo $global[0];

If you wanted to get really crazy, you could extract() all those array members into the scope (global in your case).


include() and friends are scope-restricted. You can't change the scope that the included content applies to unless you move the calls out of the function's scope.

I guess a workaround would be to return the filename from your function instead, and call it passing its result to include_once()...

function importSomething() {
    return 'something.php';
}

include_once(importSomething());

It doesn't look as nice, and you can only return one at a time (unless you return an array of filenames, loop through it and call include_once() each time), but scoping is an issue with that language construct.


If you want ordinary variable definitions to be teleported into the global scope automatically, you could also try:

function importSomething(){
    include_once('something.php');
    $GLOBALS += get_defined_vars();
}

However, it if it's really just a single configuration array, I would also opt for the more explicit and reusable return method.


I know this answer is really late for this user, but this is my solution:

inside your function, simply declare any of the vars you need to ovewrite as global.

Example:

Need to have the $GLOBALS['text'] set to "yes":

Contents of index.php:

function setText()
{
    global $text;
    include("setup.php");
}

setText();
echo 'the value of $text is "'.$text.'"'; // output: the value of $text is "yes"

Contents of setup.php:

$text = "yes";

The solution is similar to mario's, however, only explicitely globally-declared vars are overwritten.


All variables brought in from an included file inherit current variable scope of the including line. Classes and functions take on global scope though so it depends what your importing.

http://uk.php.net/manual/en/function.include.php (Final Paragraph before example)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜