Jump to content

How do you access to a variable in a class from another class?


JongMin

Recommended Posts

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

 

Link to comment
Share on other sites

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.)

Link to comment
Share on other sites

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.