1

Topic: static or non-static funtions?

I'm new to OOP PHP. I have learn OOP, but with Java. The basics are the same but some things are different.

I see that Jon uses static methods in his examples and Doctrine have some as well. What I am wondering about is which functions should be static and which should not? Should most of them be non-static? What are the best practices and/or the theory behind it?

I have an example:
In my User class extending BaseUser (we are talking Doctrine here). When I'm making a function to get a spesific user by id, what would be the best here? static or not?

I guess i need to understand in which situation to use static functions and which not to use them.


I realise that this is not php spesific, but I haven't encountered this question the little time I have used java.

Last edited by harri (2010-06-03 16:31:19)

2

Re: static or non-static funtions?

Hey Harri,

Static methods are generally considered evil in the world of OOP since they are essentially namespaced functions, however they do have a place in certain use cases. For example, when you're building a simple application with only one database connection for your models, a static method for User::FindAll(); makes plenty of sense and reads well.

The alternative would be some sort of dependency injection like

$u = new User($conn);
foreach($u->findAll() as $user)
{
// iterate here...
}
this would obviously get cumbersome and repetitive. Also, static methods are parsed more efficiently by the parser.

my 2 cents...