Back $ this-something to another value after using the value of a previous assignment is a wrong practice?

1

I have the following example:

<?php

class Classe {

   public function calcula(){
      $resultado = ($this->valor * 2);
      $this->valor = $resultado;
      return $resultado;
   }

   public function valor(int $valor = 10){
      $this->valor = $valor;
      return $this;
   }

}

$classe = new Classe;

echo $classe->valor(2)->calcula();
echo '<br>';
echo $classe->calcula();
echo '<br>';
echo $classe->calcula();
echo '<br>';
echo $classe->calcula();

Example on ideone .

I will not use this for anything, in the method that I ended up falling in this context I managed to solve otherwise, but I was in doubt because this seemed wrong to me:

  

If this is a pro solution that I need, is it a wrong practice to do this in my code?

    
asked by anonymous 20.11.2017 / 20:23

1 answer

3

Is not it easier to use __construct , young?

In your case I would make two modifications: I would add a constructor leaving a default value for the property. And you have defined the property as protected or privada so it does not change externally.

class Classe {

    protected $valor = 0;

    public function __construct(int $valor = 0)
    {
        $this->valor = $valor;        
    }

}

Now I think your question is about Classe::calcula ...

Answer: I do not think it is advantageous to do this in case of a method that will calculate. If it will compute, it should return the value, and do not change the base value (the $valor property).

I'd leave the calcula method like this:

public function calcula(): int
{
    return $this->valor * 2;
}

Now one thing you should ask yourself is not "whether it's a good practice or not," but whether or not it will be useful to change the $valor value.

You may think that there are a lot of project patterns right to solve common implementation problems (though you should not stick to it) and that each situation implies a different implementation.

Just out of curiosity, a form that could be applied in the case above (I see much of this implementation of the Laravel Collection class) is the immutability pattern, which consists of returning an instance of the class itself with the value of calcula . In this case I would modify the valor method to just return a value.

Here's how it could be applied:

class Classe {

    public function __construct(int $valor = 0)
    {
        $this->valor = $valor;        
    }

    public function calcula()
    {
        return new static($valor * 2);
    }

    public function valor()
    {
       return $this->valor;
    }

}

Usage:

   $calculo[0] = new Calcula(20);

   $calculo[0]->valor(); // 20

   $calculo[1] = $calculo[0]->calcula(); // Object(Classe)

   $calculo[1]->valor(); // 40

   $calculo[2] = $calculo[0]->calcula()->calcula(); // Object(Classe)
    
20.11.2017 / 20:41