spires Posted April 19, 2010 Share Posted April 19, 2010 Hi Simple question. Is there a reason why you should use global over passing an argument into a function, or visa versa? example: Global $var = 1; function test(){ global $var; $var++; return $var; } Passing Argument $var = 1; function test($var){ $var++; return $var; } Is it just a matter of preference? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/199033-global-vs-passing-argument/ Share on other sites More sharing options...
premiso Posted April 19, 2010 Share Posted April 19, 2010 Some people use the globals for "ease of use" and not having to always add that parameter to the function. The preferred way, especially if you plan on distributing the script, is passing the variable as a parameter to the function. This way anyone should techincally be able to see how to use it and what it expects to be passed in, vs having to dig through all your code to find out which global variable it takes in etc. Quote Link to comment https://forums.phpfreaks.com/topic/199033-global-vs-passing-argument/#findComment-1044714 Share on other sites More sharing options...
KevinM1 Posted April 19, 2010 Share Posted April 19, 2010 Rule of thumb - global should never be used. Quote Link to comment https://forums.phpfreaks.com/topic/199033-global-vs-passing-argument/#findComment-1044716 Share on other sites More sharing options...
spires Posted April 19, 2010 Author Share Posted April 19, 2010 ok great. So they are in effect exactly the same. But passing arguments is the more preferred method. I never normally use global, but a few books and training courses seem talk about using it. I've never seen the point as I just pass the variable. So just thought I'd check I wasn't missing something. Thanks for that Quote Link to comment https://forums.phpfreaks.com/topic/199033-global-vs-passing-argument/#findComment-1044723 Share on other sites More sharing options...
ignace Posted April 19, 2010 Share Posted April 19, 2010 Not to mention that you can't use the function before you made sure the global variable actually contains the required value. Quote Link to comment https://forums.phpfreaks.com/topic/199033-global-vs-passing-argument/#findComment-1044729 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.