tags:

views:

75

answers:

3

Hi, can someone explain me the difference between those 2 classes? Why to use satic calls instead of an new object?

class User 
{

  protected $users = array();

/**
 * Create new user
 *
 * @param string $name Username
 * @return array Users
 */
public function create($name)
{
    $this->users[] = $name;
    return $this->users;
}
}

$u = new User();
var_dump($u->create('TEST'));

class User
{
    protected static $users = array();

/**
 * Create new user
 *
 * @param string $name Username
 * @return array Users
 */
public static function create($name)
{
      self::$users[] = $name;
      return self::$users,
}
}

$u = User::create('TEST');
var_dump($u);
+5  A: 

Non-static members are bound to a single instance. This is not what is wanted if you want a factory or a registry of instances, so we make the relevant members static instead.

Ignacio Vazquez-Abrams
A: 

Static indicates that the class is an instance class. In layman's terms you have to initialize the object only once then it will sit in memory, until the life cycle of your object is done or you explicitly destroy the object.

This means that there is one instance of this object, whereas if you create a new object every time it has memory implications.

Please note, The usage of these two classes has to be in context. There are certain classes that must be instance classes for re-use and certain classes that needs to be normal classes due to some constraints. Please define your end goal before just jumping in. And do some reading on this topic.

There are a lot of good debates and articles on the web that can explain it a better than me.

etbal
The classes are not static in the example, but rather the members of the class.
Ignacio Vazquez-Abrams
doesn't matter because that member will still be accessible and in memory whereas a non-static member needs to be created again and again. Usually what happens is there's a getInstance() that returns that member and creates one if it doesn't exist.
etbal
+2  A: 

There are a lot of Use Cases, mostly: Factory Patterns, Singletons and others. But really, it can apply to to many Situations to elaborate them all. For example, with your code: $user = User::create()->addName('foo')->addSurname('bar'); to save some lines of code.

Hannes