473,699 Members | 2,027 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

global variables

I dont think I understand them. I've read the section on scope in the
manual inside out.

I'm running PHP 5.2.0 Here is the code I'm working on:
//include_me.php
<?php
$MYVAR = array();
global $MYVAR, $a;
?>

//array1.php
<?php
require("includ e_me.php");

global $MYVAR, $a;

$sname = 'user';
$email = 'u***@yahoo.com ';
$GLOBALS['a'] = 'here';

$MYVAR['sname'] = $sname;
$MYVAR['email'] = $email;
$MYVAR['age'] = 34;

print "SNAME: {$MYVAR['sname']} <br>";
print "EMAIL: {$MYVAR['email']} <br>";
print "AGE: {$MYVAR['age']} <br>";
print "A: $a <br>";

print '<a href="./array2.php">Nex t</a>';

?>

//array2.php
<?php
require("includ e_me.php");

global $MYVAR, $a;

$sname = $MYVAR['sname'];
$email = $MYVAR['email'];

print "SNAME: $sname <br>";
print "EMAIL: {$MYVAR['email']} <br>";
print "AGE: {$MYVAR['age']} <br>";
print "A: $a <br>";

?>

When I load array1.php, I see:
SNAME: user
EMAIL: us**@yahoo.com
AGE: 34
A: here
Next

Click on Next, and I see:
SNAME:
EMAIL:
AGE:
A:

Can I preserve the changes across page loads with globals?

Thanks,
EL

Feb 13 '07 #1
5 11820
Sandman wrote:
Can I preserve the changes across page loads with globals?
No. The global keyword is used to import variables into a function's
namespace:

$a = 1;

function foo() {
global $a;
print $a;
}

foo();

What you are looking for are sessions or cookies:

http://www.php.net/session
http://www.php.net/manual/en/function.setcookie.php
JW
Feb 13 '07 #2
Sandman schrieb:
I dont think I understand them. I've read the section on scope in the
manual inside out.
Global variables are pretty much the variables you shouldn't use at all
if you plan on writing PHP applications that are stored in more than
like three files. Global variables make all kinds of problems:
- They are shared across all files of your program. If you decide to
reuse parts of your program in another project you have to make a list
of all global variables so you dont' run into collisions with the
variables of your new project.

- If you use external packages then you don't know which global
variables this package might use. Common variables like $name are easily
overwritten and hell breaks loose. This problem is known as "pollution
of the global namespace".

- Depending on the server config (register_globa ls) the visitor can send
you global variables. This makes them insecure because you can't trust
the contents of global variables. An important rule in web programming
is NEVER TRUST USER INPUT so this means SANITIZE ALL GLOBAL VARIABLES
before using them. Or... don't use them.

- Global variables in PHP are not as global as they are in other
languages where you can sometimes always see the global variables. Some
languages even have the keyword "local" to prohibit a variable from
becoming global. PHP instead has the "global" keyword to define a
variable as global. But better forget this keyword for larger projects!
The best alternative to global variables are static class variables:

class MyVars
{
static $var1='value1';
}
MyVars::$var1 = 'huba';

Side note: And using a rare (best: unique) prefix for all classnames
ensures that you can share the code with other projects without
problems. Prefixes are PHPs poor excuse for namespaces until they
hopefully become available at some point. Those ugly reverse domain
based namespaces in Java have a purpose: They ensure uniqueness.
Can I preserve the changes across page loads with globals?
Nope. Basic rule: PHP is stateless. You lose everything after the
request is served. Every PHP script on a webserver is started after a
request is made. The script can receive input in the form of four
different concepts:
G - GET data, this is the URL, variables are transferred in the
?var=value&var2 =value2. This data has "view persistence", it is tied to
the browser window. Hit F5 and the same data is submitted again. All is
stored in the URL. You can even bookmark the data. GET data is limited
in its length, it may not exceed a few kilobytes, depending on browser
limits.

P - POST data, this is normally generated when you submit a form. The
variables are transferred in a similar format to GET, but this time in
the body of the request and not in the URL. This data has "limited view
persistence". The browser may ask you if you want to resubmit the form
data if you hit F5 but normally the data is lost once the form has been
processed. POST data may be huge, in case of file uploads it can be
several megabytes big.

C - COOKIE data, this is stored in the visitor's browser if the browser
accepts cookies. Cookies data has "session persistence" or even
"multi-visit persistence", depending on the settings in the visitor's
browser and the expiration time you set for the cookie. This data is
shared across all windows or tabs a visitor opens when browsing your
site because it is bound to the domain. DO NOT RELY ON COOKIES because
visitors may choose not to accept any cookies.

S - SESSION data, this is stored on your server, by default in a simple
file in a temp directory. From the persistence point of view it is much
like cookie data, but you can't normally define how long the data will
survive. Don't expect the session data to last longer than, well a
visitor's session when browsing your site. The problem with sessions is
that you have to know which session data belongs to which visitor
because they are not implictly connected. This connection is established
with the session ID. This is a variable that has to be transfered from
request to request via the G, P or C method. The PHP session functions
are good at automatically transferring the session ID from request to
request.
This GPCS scheme is accompanied by E, the environment information about
the server on which your PHP is running. The combination EGPCS is the
default value for the configuration directive varaibles_order (see
http://de.php.net/manual/en/ini.core...riables-order). This
directive defines a) which of the data sources as input for your script
are used and b) which data comes through if there are variables with the
same name. P comes after G, so a POST variable overwrites the GET
variable of the same name.

REMEMBER: Session data is usually shared among all open windows of a
visitor just like the cookies! To store values of a multipage-form in
the session you cannot simply write the data into the session. What if
the visitor opens the same form twice? You have to work with an array
and a unique form instance identifier as key in the array. Or you use
hidden fields or store the data in the database page by page but that's
another story.

Other ways to store data permanently include all sorts of files and
databases. And if you avoid doing full page request at all by using hip
and cool Ajax technology then you can store data in javascript variables
across "background requests".
Feb 14 '07 #3
Oliver Grätz wrote:
- Global variables in PHP are not as global as they are in other
languages where you can sometimes always see the global variables. Some
languages even have the keyword "local" to prohibit a variable from
becoming global. PHP instead has the "global" keyword to define a
variable as global.
In PHP the global keyword basically pulls a variable from the global
namespace into the local namespace.

What most other languages refer to as "globals" PHP calls "supergloba ls".
There's no way to define superglobals though -- PHP defines a few on its
own (depends on your version, but in recent ones, $_POST, $_GET, $SERVER,
$_SESSIOM, $_ENV, $_FILES and $GLOBALS) and you're stuck with them.

Although I steer away from globals (in my current project, over 4000 lines
of PHP so far, and not a single global!), sometimes I really would
appreciate having a method of defining superglobals. Not going to happen
though. :-(

--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
Feb 14 '07 #4
Awesome discussion and explanation folks.

Yes, I was thinking a global was like a superglobal, but its not.

I ended up imploding my array and sending it to the next page via
POST. Ez-peazy.

Thanks,
EL
On Feb 14, 9:08 am, Toby A Inkster <usenet200...@t obyinkster.co.u k>
wrote:
Oliver Grätz wrote:
- Global variables in PHP are not as global as they are in other
languages where you can sometimes always see the global variables. Some
languages even have the keyword "local" to prohibit a variable from
becoming global. PHP instead has the "global" keyword to define a
variable as global.

In PHP the global keyword basically pulls a variable from the global
namespace into the local namespace.

What most other languages refer to as "globals" PHP calls "supergloba ls".
There's no way to define superglobals though -- PHP defines a few on its
own (depends on your version, but in recent ones, $_POST, $_GET, $SERVER,
$_SESSIOM, $_ENV, $_FILES and $GLOBALS) and you're stuck with them.

Although I steer away from globals (in my current project, over 4000 lines
of PHP so far, and not a single global!), sometimes I really would
appreciate having a method of defining superglobals. Not going to happen
though. :-(

--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!

Feb 14 '07 #5
Toby A Inkster schrieb:
>
What most other languages refer to as "globals" PHP calls "supergloba ls".
There's no way to define superglobals though -- PHP defines a few on its
own (depends on your version, but in recent ones, $_POST, $_GET, $SERVER,
$_SESSIOM, $_ENV, $_FILES and $GLOBALS) and you're stuck with them.

Although I steer away from globals (in my current project, over 4000 lines
of PHP so far, and not a single global!), sometimes I really would
appreciate having a method of defining superglobals. Not going to happen
though. :-(
I intentionally left out elaborating about the nature of the globals vs
superglobals because use of global variables is somewaht discouraged.
Even Zend tells developers to use static class variables instead. And by
the way, Defining your own superglobals is NOT impossible. You CAN use
the runkit extension (http://de.php.net/runkit) to define variables as
superglobals. But the nature of this extension as "sandbox" should tell
developers not to do so ;-) But if you find _good_ reasons to use your
own superglobals, you are free to do so.

OLLi
Feb 15 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4364
by: mark4asp | last post by:
What are the best methods for using global constants and variables? I've noticed that many people put all global constants in a file and include that file on every page. This is the best way of doing it - is it not? Once the application has loaded the page it is cached and is immediately available for other pages. With global variables - the best thing to do would be to use application variables - so long as there weren't too many...
10
17867
by: Matt | last post by:
Greetings, What are people's thoughts on global variables in C++? Why are we taught not to use them in programming? Is it true that if you are running two copies of the C program one copy can overwrite another copies global variable? I know that you could overwrite a value in a global variable from a function, but you could also do that if you pass the variable in and then out again... so how is that any different?
5
5320
by: Richard A. DeVenezia | last post by:
Dear Experts: Suppose I have global variables: x1, x2, x3 and I have a function that needs to assign a value to a new global variable x4 something like function foo () { count = 0;
2
9164
by: Patient Guy | last post by:
I have a library of functions representing a filesystem interface (essentially a file selection interface, to be used in opening/reading/writing/closing files). Heavily scripted HTML document #1, very application-like, must include the JS file for this library of functions. One reason is that it must call a function to name a "callback" function, and within its own script block, must define the callback function. The callback handles...
17
5620
by: MLH | last post by:
A97 Topic: If there is a way to preserve the values assigned to global variables when an untrapped runtime error occurs? I don't think there is, but I thought I'd ask. During development, I'm constantly running tests on imperfect code. On of the cumbersome jobs encountered is reassigning global vars their values after a close encounter with an untrapped runtime error. Rather than writing a procedure to simply reassign them all with a...
7
3138
by: Michael | last post by:
Hi newsgroup, as the subject indicates I am looking for an advice using global variables. I am not if this problem is more about style then C. If its wrong in thi group, sorry. So I have a couple of function that all need the same information (all located in the same file). By now it looks like /* file beginns */
10
2651
by: Charles O'Flynn | last post by:
As a complete newcomer (2-3 days) to PHP, although not to programming in general, I have 'dived in' to start a small project to read and parse an XML data stream. I have already worked out most of the more specialist aspects of the job but am now completely stuck on something I would have thought were simplicity itself... I need to have a large number of global variables visible inside functions - it's not possible to pass them into the...
9
8652
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang Su Gatlin, casual mention was made about using static variables as an alternative to using global variables. This caused me to think of the following: '-----Begin module code
1
29364
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have called it polluting the global namespace. This article explores what happens when the global namespace becomes polluted and how to avoid this condition. The opinions expressed in this article are those of the author alone although many have...
0
9184
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8929
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7759
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5878
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4634
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3061
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2357
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2013
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.