开发者

Using require/require_once() in a functions file

my functions.php file is just a placeholder for many different functions. I have another file settings.php that I use to store different settings. Some of the functions in functions.php will need to access some of the variables in settings.php, so I tried:

require("settings.php")

on top of the functions.php file, but that does not seem to give my functions access to the variable in settings.php. I need to put require("settings.php") in every function separately.

Is t开发者_开发百科here a way I can declare the variables in settings.php to be accessible globally to all functions defined in functions.php?

Thank you,


You need to modify your functions in functions.php to use global variables defined in settings.php.

Inside settings.php;

$var1 = "something";
$var2 = "something else";

By using the global keyword:

function funcName() {
  global $var1;
  global $var2;

 // Rest of the function...
}

Or more preferably, using the $GLOBALS[] superglobal array. Any variables declared at global scope, like I assume your settings.php vars are, will be included as array keys in $GLOBALS[]. It's a little better for readability than using the global keyword inside each function.

function funcName() {
  $y = $GLOBALS['var1'];
  $x = $GLOBALS['var2'];
 // Etc...
}


Although you've set these variables in your settings.php file, when you try to reference them in your functions it won't work. This is because variables in functions a locally scoped to the function.

To access these global variables you need to use the global keyword to bring your global variables into scope.

For example:

// Declared in settings.php
$x = 1234;


// One of your functions
function MyFunc()
{
  global $x;

  DoSomething($x);
}

You need to do this for every function where $x is accessed.

For more information see:

Variable scope - php.net docs


I do not know the details of your issue, but you may wish to use require_once() within each function. This seems to be better idea than using some global variables.


You're thinking global variables.

However that's not the best way to go.

Can you perhaps create a class?

class SomeClass
{
    private $settings;

    function __construct()
    {
        require_once($settings);
        $this->settings = $variable(s) from settings file
    }

    function some_function()
    {
        print($this->settings['something']);
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜