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)