Proper use of "getInstance" and static methods in PHP?

I don't understand a bit about the proper use of static methods in PHP.

In the scenario below:

<?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); } } ?> 

Then I give out 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(); } ?> 

Or it will print "MikeJennifer", but I was told that Example A is incorrect "because Person is not a static class."

A class cannot be declared "static" in PHP, but why is this important?

+6
source share
1 answer

In "Emergent Design," Scott L Bane describes this as a template for the first step in abstracting the creation of objects.

Day 1: no abstraction ...

 $person = new Person($id); 

Day 2: a static method to create an object for you ...

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

Why? Because now you have only one piece of code in the entire application that knows how to β€œupdate” a person, and not have many lines of code distributed among your entire application with this knowledge. If you change the way you create the user object in the future, you can simply change the static getPerson method.

Day 3+: You can decide to rely on the object builder or repository to create the object. When you decide to do this, you can update the static getPerson method to use the builder / repository, and once again the change occurs in only one place.

This is called cohesion. The presence of code in which you can make changes without opening a lot of files.

+3
source

Source: https://habr.com/ru/post/948744/


All Articles