Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of "getInstance" and static methods in PHP?

Tags:

php

I'm a bit unclear on the correct use of static methods in PHP.

In the below scenario:

<?php

class Person 
{
    public $data;

    public function __construct($id) 
    {
        // Fetch record from our data source
        switch($id){
            case 1:
                $this->data = array('id'=>1, 'name'=>'Mike');
                break;
            case 2:
                $this->data = array('id'=>2, 'name'=>'Jennifer');
                break;
            default:
                exit('Record not found!');
        }
    }

    public function getName()
    {
        return $this->data['name'];
    }

    public static function getInstance($id)
    {
        return new self($id);
    }
} 

?>

I then output the names "Mike" and "Jennifer":

Example A

<?php 

foreach(array(1,2) as $id) 
    echo Person::getInstance($id)->getName(); 

?>

Example B

<?php 

foreach(array(1,2) as $id){
    $person = new Person($id);
    echo $person->getName();
}

?>

Either will print "MikeJennifer", but I was told Example A is wrong, "because Person is not a static class".

A class can't be declared "static" in PHP though, so why should it matter?

like image 452
jtarleton Avatar asked Jul 04 '13 21:07

jtarleton


People also ask

When should I use static methods in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

When should static methods be used?

Static methods are usually preferred when: All instance methods should share a specific piece of code (although you could still have an instance method for that). You want to call method without having to create an instance of that class. You must make sure that the utility class is never changed.

What are static methods used for?

A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

Why is GetInstance static?

for a singleton pattern, getInstance IS a static method, and uses static attrs. The whole point of static is to have things associated with the class instead of a specific object. The singleton pattern guarantees that you will have one instance of an object of that type.


1 Answers

In "Emergent Design", Scott L Bain describes this as a first-step pattern in abstracting the creation of objects.

Day 1: No abstraction...

$person = new Person($id);

Day 2: a static method to build the object for you...

$person = Person::getPerson($id);

Why? Because now you only have one piece of code in your entire application that knows how to "new up" a person, rather than having many lines of code distributed amongst your entire application that have that knowledge. If you change how you build a person object in the future, you will be able to just change the getPerson static method.

Day 3+: you may decide to lean on an object builder or repository for creating the object. When you choose to do this, you could update your getPerson static method to use the builder / repository and once again the change happens in just one place.

This is called "cohesion". Having code where you can make changes without having to open lots of files.

like image 97
Fenton Avatar answered Oct 24 '22 10:10

Fenton