Question

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);
Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top