Welcome Guest!

If you do not have an account yet on The Web Squeeze forums, please Register! It’s FREE and there are many benefits:

  • Receive Fast Advice
  • Learn Programming Languages
  • Get Professional Website Reviews
  • Quick Troubleshooting Assistance

> Using Global Variables Inside Functions

This is a discussion on Using Global Variables Inside Functions, within the PHP section. This forum and the thread "Using Global Variables Inside Functions" are both part of the Programming Your Website category.

 
Reply to this topicStart new topic
> Using Global Variables Inside Functions
MikeHopley
post Apr 25 2008, 06:41 AM
Post #1


Squeeze Machine
*****

Group: Mentor
Posts: 600
Joined: 15-February 08
From: UK
Member No.: 143



Right at the beginning of my PHP, I set a variable:

CODE
$host = "http://".$_SERVER['HTTP_HOST'];


I then use this variable for building URLs. It works fine for most of the PHP, but it doesn't work inside a function (it returns an empty string). Why?

I can simply set it again inside the function, but is this necessary? Why can't I call global variables from inside a function?

**edit**


Well, it works if I pass it to the function as an argument. Is that the way to go?

This post has been edited by MikeHopley: Apr 25 2008, 06:44 AM
Go to the top of the page
 
+Quote Post
Rakuli
post Apr 25 2008, 08:48 AM
Post #2


Squeeze Machine
*****

Group: Administrators
Posts: 643
Joined: 13-February 08
From: Catching the squeezed drips downunder.
Member No.: 13



Hi Mike,

You have to declare the variable as global inside the function otherwise function scope will not recognise it.

CODE
function thisFunction ()
{
     global $host;
}


Now the function will have access to whatever the the value of $host when the function is run.

Hope that helps


--------------------
Luke Dingle . com

Turn Over a Playful Leaf on Web Design -- read about the javascript cat
Go to the top of the page
 
+Quote Post
MikeHopley
post Apr 25 2008, 09:14 AM
Post #3


Squeeze Machine
*****

Group: Mentor
Posts: 600
Joined: 15-February 08
From: UK
Member No.: 143



QUOTE (Rakuli @ Apr 25 2008, 02:48 PM) *
CODE
function thisFunction ()
{
      global $host;
}


Excellent. That's far more sensible than my hack of passing unnecessary arguments.

Thanks!
Go to the top of the page
 
+Quote Post
If you found The Web Squeeze to be helpful, please donate so we can keep this site FREE, FRESH, and fortified with Web Design & Development info!
Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Collapse

> Similar Topics

    Topic Title Replies Topic Starter Views Last Action
No New Posts   1 edd 179 3rd July 2008 - 12:48 PM
Last post by: Scott
No New Posts   4 cosmicbdog 203 14th July 2008 - 12:25 AM
Last post by: Antti
No new   14 MikeHopley 372 15th July 2008 - 09:26 AM
Last post by: Rakuli
No New Posts   8 cosmicbdog 96 17th November 2008 - 06:56 AM
Last post by: rich97