Jump to content

Recommended Posts

register_globals has nothing to do with variable scope.

 

To use a main program variable in a function, you pass it into the function as a parameter when you call the function. If you have a piece of data, like a configuration setting or a database connection link, that is closely related to the use of one or more functions, then you use a class and you set a class variable to the value.

as r-it said, declare it as global in the main program.  Example:

<?php
   global $something;

   function a() {
      echo $something;
   }

   function b() {
      echo $something;
   }
?>

 

But that is bad programming practice. The better programming practice would be to specifically pass it to the function and return it, or else pass it by reference.  The better better programming practice is to follow PFMaBiSmAd's advice.

 

You could also declare it as a global constant using define(); but you won't be able to modify its value.

 

Ideally, as PFM said, you'd use a class to deal with this kind of stuff...

 

For a smaller scale solution you could reference the variable using $GLOBAL['varname'] within your functions. This isn't the smartest way to do it ( can make debugging tricky ), but in a small app is manageable

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.