I am working on some PHP classes, I have a session class used to set and get values to session variables, I will need to have access to this session class object in every other class so I made a singleton method in the session class and then in other class’s methods I can call the session object like this….
$session = Session::getInstance();
This will return the session object to me to use or else start a new session object if one has not been started yet.
So my question, if I have a user class and a database class and each class had 10 methods in each that needs to access the session object, then would I need to run the code above inside each and every method or just 1 time inside the class and then all methods would have it? I am new to this so I am not sure??? Thanks
In a Singleton pattern, you would indeed have to do that.
An alternative might be to add the session object as a protected member
$sessionof your class in the constructor, and then accessing it from each method as$this->session.If you want to read some broader discussion about how to arrange and use helper and library objects in PHP, I asked a related SO question once that yielded interesting answers.