scriptygoddess

03 Dec, 2002

declaring variables as "global" in php

Posted by: Jennifer In: Lessons learned

I was just working on implementing this credit card validation script . I had been working with a similar version that was on devarticles.com and the script they have there did NOT work. (The one I linked DOES work!) In any case, I noticed in the one that didn't work, the author was declaring a lot of variables as "global" (this wasn't the reason why the script wasn't working), but it made me wonder when you needed to declare variables as global and when you didn't. A little search on Google, and I found this explanation here: (I am quoting them verbatim – on a side note, for those of you who are interested in a php site for newbies, phpbeginner.com looked pretty good!)

…. Here we declare $variable1 to be 'global'. When a variable is not declared as global inside a function, PHP basically goes 'ok, since this is NOT a global variable we'll make a "new"$variable1 JUST for use INSIDE this function. And when the function is finished executing, we can jut throw that variable away! This approach is GREAT when we want to use variables as temporary things, but not when we want what we're doing to affect the rest of our script's 'world'. When we declare a variable as 'global' it makes the PUBLIC version of that variable available to the function, and any changes we make to are permanent! Also of importance: if you declare a variable as global inside a function–and the variable did not exist in the script beforehand–it does now, so be careful.

One last note before I get on with things: if you declare a variable to be 'global' inside one function, then it is global–but only for that function, you must re-declare it as 'global' in each function that you want to work with it globally.

1 Response to "declaring variables as "global" in php"

1 | Tudy

December 3rd, 2002 at 6:16 pm

Avatar

Jen this was great.. I bookmarked it. I also found this site
http://www.free2code.net/tutorials/php/Introduction_to_PHP

That goes into even more detail for the absolute beginner like me. Im going to learn this stuff if it kills me. Thanks for you links.

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements