Page 1 of 1

static or dynamic methods?

Posted: Tue May 19, 2009 5:06 am
by jazz090
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:

Code: Select all

<?php
class abc {
    protected static $_counter = 0;
    public $num;
    public function __construct(){
        self::$_counter++;
        $this->num = self::$_counter;
    }
}
$a = new abc();
echo $a->num; // 1
$b = new abc();
echo $b->num; // 2
?>
but then again if you remove the protected scope, you can access it directly and the dynamic usage becomes completly obsolete.

Code: Select all

<?php
echo abc::$counter;
?>

Re: static or dynamic methods?

Posted: Tue May 19, 2009 11:52 am
by Christopher
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.

Re: static or dynamic methods?

Posted: Mon May 25, 2009 10:21 am
by josh
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.

With objects:

Code: Select all

 
$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;
 }
}
 

Code: Select all

 
 
class Obj
{
  public function __construct( )
 {
  $this->factory = Factory::getInstance(); // easier to type but how do you use different factories for different environments?
 }
}