homepage Welcome to WebmasterWorld Guest from 54.234.147.84
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
making a variable global in a function
..but why does it not work?
skylla




msg:3471080
 12:54 pm on Oct 7, 2007 (gmt 0)

Why would the next example echo out absolutely nothing? Something simple, right? my php 5.2.3 configuration?

in advance, thanks for the help...


$my_var = 'Hello World';
function test_global() {
global $my_var;
echo $my_var;
}
test_global();

 

ahmedtheking




msg:3471167
 3:01 pm on Oct 7, 2007 (gmt 0)

It should be:

$myvar = "x";
global $myvar;

function myfunc () {
echo $myvar;
}

myfunc();

cameraman




msg:3471202
 4:24 pm on Oct 7, 2007 (gmt 0)

skylla, you have it right. I tested it on mine and it works just fine. Something else is going on.
What happens if you echo $myvar below the function call?

skylla




msg:3471226
 5:39 pm on Oct 7, 2007 (gmt 0)

an echo out after the function is called works ok, i.e. it echos 'hello world'.

hmmm, I thought for some time I was missing something simple.

I have now tested the 'script' on a fresh and barebone virtual localhost and it works fine. However, if I call the above function from a page via another script on the same localhost it fails.

This other script enables me to include a page via an http query, i.e. http://example.com/index.php?page=temp calls http://example.com/content/temp.php

I will post the code in the next post. Any help is appreciated!

[edited by: dreamcatcher at 5:48 pm (utc) on Oct. 7, 2007]
[edit reason] Use example.com, thanks. [/edit]

skylla




msg:3471231
 5:45 pm on Oct 7, 2007 (gmt 0)

////////////// index.php ////////////

<?php
require_once('page_includer.php');
includeContentFile();
?>

////////////// page_includer.php (stripped out copyright) //////////

<?php
$path = 'content';

# Extension of the content files
$extension = 'php';

# Default content file to select if no parameter is given.
$default = 'home';

# Displays an error message.
function showError($msg)
{
echo "<h1>Error</h1>\n";
echo "<p>" . $msg . "</p>\n";
}

function showErrorPage() {
require_once(ERROR_PAGE);
}
# Make security checks and include the content file specifyed by the parameter.
function includeContentFile() {
global $path, $extension, $default;

# Read page parameter.
$filename = isset($_GET['page'])? $_GET['page'] : $default;

# Check if a page was selected.
if (! $filename) {
showErrorPage();
return;
}

# Check for illegal characters.
foreach (array('.', '/', '\\') as $illegal) {
if (false!== strpos($filename, $illegal)) {
showErrorPage();
return;
}
}

# Check file existence.
$fullpath = realpath(sprintf('%s/%s.%s', $path, $filename, $extension));
if (! file_exists($fullpath)) {
showErrorPage();
return;
}

# Finally include file.
include($fullpath);
}
?>

////////////// content/temp.php //////////////////

<?php
$my_var = 'Hello World';
function test_global() {
global $my_var;
echo $my_var;
}
test_global();

//echo $my_var;
?>

skylla




msg:3471237
 5:51 pm on Oct 7, 2007 (gmt 0)

So, to recap:

the function in temp.php called via by http://example.com/content/temp.php works fine!

it fails to work however when temp.php is called via an http query http://example.com/index.php?page=temp

Thanks for your input!

[edited by: dreamcatcher at 5:52 pm (utc) on Oct. 7, 2007]
[edit reason] Use example.com, thanks. [/edit]

Habtom




msg:3471525
 5:25 am on Oct 8, 2007 (gmt 0)

it fails to work however when temp.php is called via an http query http://example.com/index.php?page=temp

That is more likely due to the $fullpath holding a path which is not valid.

Try printing the path before including it to see if you have it all valid, otherwise I don't see why it shouldn't work that way.

skylla




msg:3471654
 9:52 am on Oct 8, 2007 (gmt 0)

I'm afraid the problem is not with the said page not being included. It is the global declaration of the $my_var within the function which fails to work when the page is called via the 'page includer' script: i.e. the bit of code in this post prints the second last line, no problem, but the function does not work, unless I call the page DIRECTLY - /content/temp.php

When $my_var is not made global PHP kindly gives a notice that $my_var is not defined; if it is made global (global $my_var;), the notice disappears! Further proof that the script can be read.

Is there a maximum of variables which can be declared globally? Not that I'm aware and certainly not within this scope.

I have been able to reproduce this on my remote host with PHP 4.x


$my_var = 'Hello World';
function test_global() {
global $my_var;
echo $my_var;
}
test_global();
echo 'this little code is executed, although the function does not work as it should';

cameraman




msg:3471943
 4:44 pm on Oct 8, 2007 (gmt 0)

HAH! I've got it.

Consider this:
<?php
$vbl = 6;
function outer() {
$myvar = 'hello';

function inner() {
global $myvar,$vbl;
echo $myvar;
echo "<br>\n";
echo $vbl;
} // end inner()

inner();
} // end outer()

outer();

?>

This is basically what you're doing. We know that $vbl is definitely a global variable. $myvar, since it's declared inside the outer() function, is not, so it's not surprising that the inner() function can't find it. Your includeContentFile() is acting just like outer() with part of its body being inner() from the include.

I expect your brain is probably already whirring with the solution, but for those who haven't had their morning coffee yet, the fix is to change the structure a little to make sure the file gets included in the global scope, that is, outside any function body. For example, includeContentFile could set up and return an array of files to include, then the script that calls includeContentFile does the actual inclusion/execution. An alternate fix would be to declare variables like $myvar using the $_GLOBAL superglobal, but that would be sort of a pain to remember to do as you're writing the 'subscripts'.

skylla




msg:3471955
 5:00 pm on Oct 8, 2007 (gmt 0)

'Hello world!' it now proudly displays!

Crikey, never realised I'm dealing with a function within a function. It's a strange construction having the file included within the first function, so instead returning the $fullPath variable solves it!

Thank you very much for helping out, not very obvious from the outset, but now you've pointed it out it very much is. I hope someone else can learn from this too!

S.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved