php – Set values ​​inside or outside the method?

Question:

I'm studying about passing parameters in PHP. I want, for example, to use a certain method that needs to receive two values, I have the following codes:

Example 1

In class :

class Exemplo {
        protected $var1, $var2;
        
        public function setVar1($value){
           $this->var1 = $value;
           return $this;
        }
        public function setVar2($value){
           $this->var2 = $value;
           return $this;
        }
    
        public function exemplo(){
           $dado1 = $this->var1;
           $dado2 = $this->var2;
        }
}

And the call

 $exe = new Exemplo();
 $exe->setVar1('dado1')
     ->setVar2('dado2')
     ->exemplo();

Or

Example 2

In class :

class Exemplo {
   public function exemplo($var1, $var2)
   {
      $dado1 = $var1;
      $dado2 = $var2;
   }
}

And the call

 $exe = new Exemplo();
 $exe->exemplo('dado1', 'dado2');

Apparently the two codes do the same, and Example 2 is clearly much simpler to do, I would like to know what the difference between them is besides writing, and/or what would be the most correct (if any) or better form. And in terms of security and speed, do they have a difference?

Answer:

Well, in this question the two examples are not equivalent. In both the exemplo() method doesn't actually do anything useful. Assigning values ​​to local variables and doing nothing with them makes no sense. So do the simplest one, the one with the fewest steps. I would say this is example 2, but even that is unnecessary.

If the method were:

public function exemplo($var1, $var2) {
    $dado1 = $this->var1 = $var1;
    $dado2 = $this->var1 = $var2;
}

I put it on GitHub for future reference .

Then the difference is that the second one you guarantee that the two properties are assigned together. It's an atomic operation. In the first example it is possible to do it separately.

There is no relevant speed difference. Security itself doesn't change anything. It's a matter of intention. If the two properties need to be changed together, the first example is wrong. If they need to, even if they eventually change independently, the second is wrong.

So there's no better, there's right and wrong. And it depends on the situation.

In this example I would say whatever. In a more concrete example, it depends. There are a lot of little rules that people write and many programmers follow that don't make sense. If you follow blindly, you end up doing it wrong.

Generally speaking, you should create setter methods if you have a good reason to. If you can't find a good justification for creating them, don't.

Scroll to Top