Solved

EASY: question on PHP's scope

Posted on 2007-03-26
3
222 Views
Last Modified: 2008-03-06
Greetings, I have the following problem:

-in ASP, I used to write all the initialization code for my web applications in a separate file; I would declare my variables in the "main" page, include the .asp file with the initialization function and then invoke the function; during this function, all the initialization variables would be initialized, and having declared them beforehand they would still be readable after the initialization function has returned.

It seems that in Php I cannot do this, as the variables which I initialize lose their value when the function returns, even if I have variables with the same name declared in the previous level of the scope.

How do I solve this problem? Is there a better way other than:

a) writing an initialization function for every variable, whose value is returned by the function itself;
b) copy-pasting the initialization code in the same page where I use the variables.

Many thanks.
0
Comment
Question by:Emanuele_Ciriachi
  • 2
3 Comments
 
LVL 24

Accepted Solution

by:
glcummins earned 250 total points
ID: 18793570
You can use the 'global' keyword in your functions:

function myFunction()
{
   global $var; // This is a variable that was initialized in the master script

   $var = 'value;  // Now you are changing the value of $var for the entire script.
}
0
 
LVL 11

Expert Comment

by:JamesCssl
ID: 18793574
use the keyword global before the variable name:

global $var1, $var2;
0
 
LVL 24

Expert Comment

by:glcummins
ID: 18793577
More information can be found here: http://www.php.net/global
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now