Jump to content

Getting Global Scope to work


jaunty_mellifluous

Recommended Posts

<?php


function getglobal() {

global $my_global;

echo "The value of \$foobar is '$foobar' <br />";


}

$my_global = 20;

getglobal();

?>

 

It's supposed to give the result,

 

'The value of $my_global is '20';

 

 

But instead when I try it, its giving me

 

Notice: Undefined variable: foobar in C:\wamper\www\php\index.php on line 17

The value of $foobar is ''

 

 

So I don't really understand what's happening and why it's not working.

Link to comment
https://forums.phpfreaks.com/topic/214694-getting-global-scope-to-work/
Share on other sites

<?php


function getglobal() {

global $my_global;

//variable $foobar is not defined. Therefore commmenting below line out
//echo "The value of \$foobar is '$foobar' <br />"; 

echo "The value of \$my_global is '$my_global' <br />"; 

}

$my_global = 20;

getglobal();

?>

 

The above will output:

 

The value of $my_global is '20'

function getglobal((int)$value) {

return "The value of $my_global is ".$value." <br />"; 

}

$my_value = 20;
echo getglobal($my_value);
?>

 

This is purely to illustrate; try not to waste globals (memory) on trivial things like this as it is a waste of memory, if you want a global, use a constant (define('MyGlobal', 20);) then at least this way you don't need to explicitly request them into a function, they are available throughout the scope of your project so long as they are defined first.  This is what constants are for.

 

In this example, I have used (int) this is just for type hinting, technically for use in classes, but I find them to be just as good for functions, this just tells php that whatever is passed into this function has to be an integer, else php needs to throw an error, similar to this - "string/boolean given expected integer"

 

And functions return values from them, realistically echo's are for debug when in context of functions, either that or print_r...

 

Rw

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.