PHP Setters/Getters and Constructor

眉间皱痕 提交于 2020-01-12 19:36:10

问题


I have been searching for this online, but I can't seem to find something that is clear enough for me to understand. I have seen "similiar" questions on here 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");
  1. Should I declare and access my private fields through setters and getters or through the constructor?
  2. Which one is the best practice?
  3. I understand the purpose of a constructor(maybe not), but what is the point of having a constructor if I can declare and access my private fields through setters and getters?

Please note...this is my first time using OOP with web development and PHP, and I'm trying to learn by getting my hands "dirty" by writing some code in order for me to understand certain things in OOP. Please keep it simple.


回答1:


It is more a matter of semantics than best practice per say.

In your example, your buisness logic may determine that an animal always needs a name. So it makes sense to construct the object with a name. If you do not want to allow an animal's name to be changed, then you don't write 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 an animal doesn't have to have, like an owner that you only write a getter/setter for i.e.

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 are always creating an animal with an owner at the same time you may want to put that in the contructor 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 type hint that your constructor needs an owner of a specific type (class). All of this is used to make it easier for you, or another developer to understand some of the requirements/logic behind your code - as well as potentially catching a bug 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);



回答2:


Should I declare and access my private fields through setters and getters or through the constructor?

In situations like this, I ask myself:

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

  • How painful is it going to be to refactor two, three, four, five or more getters/setters vs one constructor?(+Constructor)

  • How hard is it going to be to document two, three, four, five or more getters/setters vs one constructor?(+Constructor)

  • Is there going to be a default value which will be documented? (+Constructor)

  • Do I like documentation and expect people to read? (+Constructor)

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

  • Is there a set of equivalent forms (shorthand, international, nicknames) which will all be acceptable as syntatically correct for required arguments? (+Setter)

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

  • Is there a common need to stringify and parse the initial value? (+Setter)

  • Do I dislike documentation and expect people to experiment? (+Setter)

Which one is the best practice?

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

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

A constructor is implicitly invoked upon object instantiation in order to encapsulate the default state of the resulting data structure of its type.

References

  • DateTime::__construct

  • date_create

  • The DateTime class

  • date_default_timezone_get

  • date_default_timezone_set

  • Changes in PHP datetime support

  • PHP OOP: Accessor and Destructor Methods

  • Concurrency, part 4: Comparing promises frameworks in different languages – SLaks.Blog

  • CDD: Context-Driven Development




回答3:


  1. Depends. Usually one say: If it's a required dependency, use the constructor, if it's optional, use getter/setter.
  2. There is no preference for, or against one of them.
  3. The constructor contains code, that is executed right after the object is created and it should leave the object in a stable and useable state. Thats the idea behind the constructor and it doesn't work in any case, but it should give you an idea, what should go into it.

Note, that you can even implement both constructor arguments and setters for the same property, for example if you want to allow to replace property 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"



回答4:


Should I declare and access my private fields through setters and getters or through the constructor? Which one is the best practice?

Both. It depends on your needs. If need a value in certain fields you add a param to the __construct()-Method to do so. Or you can also add an optional Param to __construct to give the user the option to set the attribute

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

The contructor should initialize your attributes which need to be initialized.




回答5:


In my opinion, it is more correct to write setter's & getter's, since then, the number of properties will only grow. And the __construct can then take an array of properties of the names of the keys (property => value), and set them to properties.




回答6:


1 > That's your chose : if dependency is required, good practise use the constructor, else, use getter.

2 > for the best practise is the first,

Actually, you have a name, for your animal, but if you add a type and sex? and you want to call type, sexe or name separatly, first method is more 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 > that depends first question... BUt Globaly we are always one dependency required, for 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.
}

}


来源:https://stackoverflow.com/questions/11740145/php-setters-getters-and-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!