Jump to content

using vars in function


alin19

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.