dtf1111 2010-01-16 23:36
浏览 16
已采纳

我是否需要在类中的每个方法中获取PHP类对象?

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

  • 写回答

5条回答 默认 最新

  • duanchuang6978 2010-01-16 23:39
    关注

    In a Singleton pattern, you would indeed have to do that.

    An alternative might be to add the session object as a protected member $session of 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?