开发者

PHP $var undefined when using multiple require()

开发者 https://www.devze.com 2023-04-01 15:24 出处:网络
I\'m setting a $baseurl in a settings.php file. In my index.php, I\'ve got 3 require() in a row for the settings.php/header.php/masthead.php.

I'm setting a $baseurl in a settings.php file.

In my index.php, I've got 3 require() in a row for the settings.php/header.php/masthead.php.

When I come to echo out the $baseurl it's undefined开发者_JAVA百科. If I define the $baseurl within the header.php then it works within the header.php file.

How can I get the $baseurl to be defined within the settings.php file and usable within each require() ?


Order of inclusion

The file that sets $baseurl must be require_once() first for the subsequent files to have access to the variable.

Function Scope

If you are defining $baseurl in a function or the files are require_once() from within a function then $baseurl will be trapped in that functions scope. This would the case if settings.php looked something like:

<?php
function setup_config() {
    $baseurl = 'http://www.example.org';
}

Or requiring from within a function

<?php
function include_a_file($file) {
    require_once 'my/base/path/' . $file;
}

This is documented in the Variable Scope portion of the PHP Manual.

One way to work around this is to add $baseurl as an element in $GLOBALS array instead of as a standalone variable:

$GLOBALS['config']['baseurl'] = 'my/base/url/';

Note I have added the ['config'] element to namespace your config away from anything else you may be tempted to place in $GLOBALS.

variable unset()

Another possibility is that you might be calling unset($baseurl) somewhere else in the code, which would be marking the variable as undefined.


If you define it in settings.php, it should be available in the global scope of all the included scripts. When you enter a function, the scope changes so the variable won't be available unless you 'import' it by declaring global $baseurl; at the start of the function (not advised, though).


If settings.php is included first, and $baseurl is defined as a global variable in settings.php, it will be available in all subsequently included files. If the variable is defined inside a function in settings.php, it will need to be defined as a global there:

$GLOBALS['baseurl'] = 'theurl';

If it is accessed within a function in any of the subsequently included files, it will need to be accessed via $GLOBALS[] there too:

echo $GLOBALS['baseurl'];

If you are expecting to access a global variable from multiple files, it is highly recommended to always use the $GLOBALS[] array since it remains clear in any scope that the variable is being set and accessed globally.


If you require() the files in a function, the variables are defined in the scope of the function: They are not global.

Use $GLOBALS['baseurl'] = '...'; in settings.php

0

精彩评论

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