Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
I've never been so sure about the two. I know how to use them and the fact that static refers to all instances of the instantiated objects (or the entire class as general) and dynamic refers to each instantiated object individually. But I never got to find out which one to use at which situations i.e. which one would work best for specific tasks? (or HAS to be used for specific tasks)
The only good example of static usage I know is too keep track of number of instances created:
The other main uses are for implementing Singleton and for when there is a single system resource that all instances needs to reference. But in all of those cases, it would probably be better to composite another object that manages it.
If you're not sure than you want an object ( an "instance" ). Use static variables + methods only when the data or behavior conceptually applies to the "class", not the individual instances. For instance I will use a class constant ( which is static but immutable state ) to encapsulate repeated literals. Another use is factory methods, although then I would almost rather have a factory instance then a factory class, the problem is if you use static calls it is harder to extend your system, and you loose out on the ability to create "special case" objects. For instance if your factory is static it would be more difficult to tell some component to use a different type of factory.
$factory = new Factory_For_Testing_Only();
$myObj = new Obj( $factory ); // could be an instance of any class that implements the right INTERFACE
class Obj
{
public function __construct( $factory )
{
$this->factory = $factory;
}
}
class Obj
{
public function __construct( )
{
$this->factory = Factory::getInstance(); // easier to type but how do you use different factories for different environments?
}
}