alin19 Posted October 22, 2008 Share Posted October 22, 2008 i have a var and i want to use it in all functions and in the main project also, how do i declare it? Quote Link to comment https://forums.phpfreaks.com/topic/129571-using-vars-in-function/ Share on other sites More sharing options...
r-it Posted October 22, 2008 Share Posted October 22, 2008 declare it as global and set register_globals off Quote Link to comment https://forums.phpfreaks.com/topic/129571-using-vars-in-function/#findComment-671715 Share on other sites More sharing options...
PFMaBiSmAd Posted October 22, 2008 Share Posted October 22, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/129571-using-vars-in-function/#findComment-671754 Share on other sites More sharing options...
.josh Posted October 22, 2008 Share Posted October 22, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/129571-using-vars-in-function/#findComment-671798 Share on other sites More sharing options...
PFMaBiSmAd Posted October 22, 2008 Share Posted October 22, 2008 The global keyword does not have any meaning when it is placed in the main program scope. Quote Link to comment https://forums.phpfreaks.com/topic/129571-using-vars-in-function/#findComment-671804 Share on other sites More sharing options...
discomatt Posted October 22, 2008 Share Posted October 22, 2008 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 Quote Link to comment https://forums.phpfreaks.com/topic/129571-using-vars-in-function/#findComment-671820 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.