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
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'

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.