JongMin Posted August 27, 2013 Share Posted August 27, 2013 Hi, I need to hold a value globally which could be user ID or DB object and so on. The value must be accessible from any classes or files. In this case which design pattern would you use? Superglobals? Constants? Singleton? Static? Thanks in advance Quote Link to comment https://forums.phpfreaks.com/topic/281593-how-do-you-access-to-a-variable-in-a-class-from-another-class/ Share on other sites More sharing options...
requinix Posted August 27, 2013 Share Posted August 27, 2013 Forget "design patterns" for a second, okay? That's just a fancy term for a group of more fancy terms for how you architect your code. What values? Do they change? Where do their values come from? Where do you need to use them? How are they used? Quote Link to comment https://forums.phpfreaks.com/topic/281593-how-do-you-access-to-a-variable-in-a-class-from-another-class/#findComment-1446953 Share on other sites More sharing options...
Muddy_Funster Posted August 27, 2013 Share Posted August 27, 2013 It all depends on what the value is, which you havn't given enough detail about. But as requinix said (with a great deal more elequence), your thinking about this all wrong. Quote Link to comment https://forums.phpfreaks.com/topic/281593-how-do-you-access-to-a-variable-in-a-class-from-another-class/#findComment-1446954 Share on other sites More sharing options...
mac_gyver Posted August 27, 2013 Share Posted August 27, 2013 something like a user ID (or an instance of a user class) wouldn't be "I need to hold a value globally". it would be an input value that you pass into a class/class-method as a call time parameter. what happens when an administrator needs to manage a list of other user ID's or one user is viewing the profile information of another user? the user id that any code operates on, could come from a session variable, a form/url submission, the result of another function/method, ... your classes/class-methods need to be general purpose enough so that the input data values they use are determined at call time, not hard-coded into them. something like a DB object, that provides the method(s) needed to interfacing to the underlying data layer, that classes are dependent on to function, should be passed into the class, again as a call time parameter, either in the constructor or in a specific setter method, for the same reason as given above (general purpose code that operates on different input data/data layer based on how you use/call it, not not what's hard-coded into it.) Quote Link to comment https://forums.phpfreaks.com/topic/281593-how-do-you-access-to-a-variable-in-a-class-from-another-class/#findComment-1446965 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.