1

I have a super class called LClass. Then I create other classes, which extend LClass. For example this are classes for tables in database. ( user, order, etc...) In each of these classes I use some static function getRecordById($id), which returns some array. The difference between these functions, they use different table names for executing. I want to put this static function getRecordById($id) in LClass. The problem is, that function is static, and for this I need some static variables to be set before I do something like $someUser = user::getRecordById($id).
Or any other suggestions?

7
  • 2
    Static is evil. You've proven that. Commented Dec 5, 2012 at 10:54
  • Is it better to do $user = new user; before $someUser = user::getRecordById($id); ? Commented Dec 5, 2012 at 10:56
  • Karimov: yes, much better. According to the last phrases from your question - you need to store some state. That is what object are used for. Commented Dec 5, 2012 at 10:59
  • edit, I meant $user = new user(); I considered, that we can also have getRecordByName($name) function. So $id in constructor does not always help. Commented Dec 5, 2012 at 11:00
  • Actually I am a bit wrong with placing the previous comment :) That was the answer for @Tom. Commented Dec 5, 2012 at 11:05

2 Answers 2

3

Programming exclusively using static methods is not object oriented programming, it's "class oriented" programming. And it's essentially the same as procedural code with a sliver of namespacing. Static methods have their use, but it is limited. Static methods should never do the main work of a class.

Read How Not To Kill Your Testability Using Statics.

Sign up to request clarification or add additional context in comments.

7 Comments

Yes, but in classes can also be some not static functions. In case of saving some records.
Yes, there can be. There should be. If you start instantiating your objects and use non-static methods, then you've started practicing OOP.
@deceze if you make your answer less extreme by providing an example of a situation where static makes sense, I'll not write my own answer! :)
@markus I have written about that long and hard in the linked article. It's actually very moderate, not extreme at all. :) Changed the answer a bit to reflect that.
Well, I agree, I try to avoid static... but telling the OP that it's evil may not be the best thing to do. Anyways, your answer is now more balanced for my taste. And nice article, btw.
|
0

Avoid static methods. As simple as that.

Regarding your comment on the original question, consider the following code example:

$user = new User($id);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.