Pwnna
Pwnna

Reputation: 9538

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 be included in the global scope?

Upvotes: 2

Views: 8213

Answers (5)

devplayer
devplayer

Reputation: 666

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.

Upvotes: 2

mario
mario

Reputation: 145512

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.

Upvotes: 4

Paystey
Paystey

Reputation: 3242

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)

Upvotes: 0

alex
alex

Reputation: 490499

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).

Upvotes: 6

BoltClock
BoltClock

Reputation: 724342

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.

Upvotes: 6

Related Questions