Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End php variable problems Re: php variable problems

#66761
gno
Member

Clokey2k, that is not true. At least, neither when I think back at my past experiences on this point, nor what I read from the man-page.

There’s only two scopes in PHP. The global scope and the local scope. Include, include_once, require or require_once does not make new scopes, nor change scopes, for the included files.

The local scope is within functions and classes, the global scope is the rest. Take a look at the following example:


$a = '$a is global!';

function test() {
$a = '$a is local!';
}

test();

echo $a; // Output: $a is global!

?>

One problem I’ve seen quite often is people using functions to get different parts of the website, and then causing them self scope-trouble. Like the following example.


function getPart($part) {
require ('path/to/'.$part.'.php';
}
$contentForHeader = 'Hi, im header!';
getPart('header');
?>

Files included via the “getPart()” function, will be part of that functions local scope (a seperate scope for each call to that function) and will thus not have access to the $contentForHeader Variable.

If one wish to use such functions, you could make a “super global array” for information you wish to use all over your site. Calling that “$data” and putting the line “global $data;” inside your getPart function would allow this.