PHP Setters / Getters and Constructor

I searched this online, but I cannot find something that is clear enough for me to understand. I saw here “similar” questions about this in Java.

class animal{ private $name; // traditional setters and getters public function setName($name){ $this->name = $name; } public function getName(){ return $this->name; } // animal constructors function __construct(){ // some code here } // vs function __construct($name){ $this->name = $name; echo $this->name; } } $dog = new animal(); $dog->setName("spot"); echo $dog->getName(); // vs $dog = new animal("spot"); 
  • Do I have to declare and access my personal fields through setters and receivers or through the constructor?
  • Which one is the best?
  • I understand the purpose of the constructor (maybe not), but what is the point of creating a constructor if I can declare and access my personal fields through setters and getters?

Please note ... this is my first experience using OOP with web development and PHP, and I am trying to learn when my hands are dirty by writing some code so that I can understand some things in OOP. Please keep it simple.

+6
source share
6 answers

This is more a matter of semantics than a best practice for each of them.

In your example, the logic of your business can determine that the animal always needs a name. Therefore, it makes sense to build an object with a name. If you do not want to resolve the name of the animal that needs to be changed, then you are not writing a setter.

i.e.

 class Animal { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } 

You may have other properties that the animal should not have, for example, the owner that you only write a getter / setter for ie

 class Animal { private $name; private $owner; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } public function setOwner($owner) { $this->owner = $owner } } 

But if you find that you always create an animal with the owner at the same time, you may want to put this in the counterparty’s signature for convenience

 class Animal { private $name; private $owner; public function __construct($name, $owner = null) { $this->name = $name; $this->owner = $owner; } public function getName() { return $this->name; } public function setOwner(Owner $owner) { $this->owner = $owner } public function getOwner() { return $this->owner; } } 

If the owner is another class in your application, you can enter a hint that your constructor requires an owner of a certain type (class). All this is used to make it easier for you or another developer to understand some of the requirements / logic of your code, as well as to potentially catch an error here or there.

 class Owner { private $name; public function __construct($name) { $this->name = $name; } } class Animal { private $name; private $owner; public function __construct($name, Owner $owner = null) { $this->name = $name; $this->owner = $owner; } public function getName() { return $this->name; } public function setOwner(Owner $owner) { $this->owner = $owner } public function getOwner() { return $this->owner; } } // Create a new owner! $dave = new Owner('Farmer Dave'); // a standard php empty object $otherObj = new \stdClass(); // Create a new animal $daisy = new Animal('Daisy'); // Farmer dave owns Daisy $daisy->setOwner($dave); // Throws an error, because this isn't an instance of Owner $daisy->setOwner($otherObj); // Set up Maude, with Dave as the owner, a bit less code than before! $maude = new Animal('Maude', $dave); 
+5
source
  • It depends. Usually they say: if this is the required dependency, use the constructor; if it is optional, use getter / setter.
  • No preference or against one of them.
  • The constructor contains code that runs immediately after creating the object, and it should leave the object in a stable and usable state. This is the idea of ​​a constructor, and it by no means works, but it should give you an idea of ​​what should be included in it.

Note that you can even implement both constructor arguments and setters for the same property, for example, if you want to allow property replacement later.

 $bingo = new Dog; echo $bingo->getName(); // DogHasNoNameException <-- maybe better as constructor argument? $bingo = new Dog('Bingo'); echo $bingo->getName(); // "Bingo" $spike = new Dog; // Missing argument $bingo->setName('Spike'); // Or maybe "rename()" ;) echo bingo->getName(); // "Spike" 
+2
source

Do I have to declare and access my personal fields through setters and getters or through the constructor? Which one is best practice?

I. It depends on your needs. If you need a value in certain fields, you add a parameter to __construct() - A way to do this. Or you can also add an optional Param parameter to __construct to give the user the ability to set the attribute

I understand the purpose of the constructor (maybe not), but what is the point of having a constructor if I can declare and access my private field through setters and getters?

The contractor must initialize your attributes, which must be initialized.

+2
source

In my opinion, it is more correct to write a setter and getter, since then the number of properties will only grow. Then __construct can take an array of key name properties (property => value) and set them in the properties.

+2
source

Do I have to declare and access my personal fields through setters and receivers or through the constructor?

In such situations, I ask myself:

  • Why should I create a method just to hold one line? (+ Constructor)

  • How painful will it be to reorganize two, three, four, five or more getters / setters against one constructor? (+ Constructor)

  • How difficult will it be to document two, three, four, five or more recipients / installers against a single constructor? (+ Constructor)

  • Will there be a default value to be documented? (+ Constructor)

  • I love the documentation and expect people to read? (+ Constructor)

  • Will the initial value be undefined? (+ Setter)

  • Is there a set of equivalent forms (abbreviated, international, nicknames) that will be acceptable if it is syntactically correct for the required arguments? (+ Setter)

  • Is there a set of optional arguments with default values? (+ Setter)

  • Is there a general need for rigorous and parsing of the original value? (+ Setter)

  • I do not like documentation and expect people to experiment? (+ Setter)

Which one is the best?

The Date object seems to be the most complex class in most languages, so its PHP implementation will be a good reference for best practices.

What is the point of creating a constructor if I can declare and access my personal fields through setters and getters?

The constructor is implicitly called when the object is created to encapsulate the default state of the resulting data structure of its type.

CDD: roles with context-sensitive development - creator, object, behavior

References

+2
source

1> What did you choose: if dependency is required, good practice uses a constructor, otherwise use getter.

2> for best practice is the first

Actually, you have a name for your animal, but if you add the type and gender? and you want to name a type, sexe or name separately, the first method is better than the second.

 class animal{ private $name, $type, $sex; // traditional setters and getters public function setName($name){ $this->name = $name; } public function setSex($sex){ $this->sex = $sex; } public function setType($type){ $this->type = $type; } public function getName(){ return $this->name; } public function getSex(){ return $this->sex; } public function getType(){ return $this->type; } // animal constructors function __construct(){ // some code here } } $dog = new animal(); $dog->setName("spot"); $dog->setSexe("male"); $dog->setType("dog"); echo $dog->getName().' is a '.$dog->getType().'('.dog->getSex().')'; 

3>, which depends on the first question ... BUt Globaly always requires one dependency, for a sample:

 class animal{ private $name, $type, $sex; // traditional setters and getters public function setName($name){ $this->name = $name; } public function setSex($sex){ $this->sex = $sex; } private function setType($type){ // if type is string ( cat, dog, lion ) and you want // to linked string in an id in your database (1, 2, 3...). // you want to call your database connection ( declared in you constructor) // and search type id here. $this->type = $type; } public function getName(){ return $this->name; } public function getSex(){ return $this->sex; } public function getType(){ return $this->type; } // animal constructors public function __construct($type){ // for sample you want to open your database here this->setType($type); } public function __destruct(){ // and you want to close your connection here. } } 
+1
source

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


All Articles