• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 232
  • Last Modified:

EASY: question on PHP's scope

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.
  • 2
1 Solution
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.
use the keyword global before the variable name:

global $var1, $var2;
More information can be found here: http://www.php.net/global
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now