Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP include_once inside a function to have global effect

Tags:

scope

php

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?

like image 369
Pwnna Avatar asked Aug 25 '26 20:08

Pwnna


2 Answers

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

like image 174
alex Avatar answered Aug 27 '26 10:08

alex


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.

like image 35
BoltClock Avatar answered Aug 27 '26 09:08

BoltClock