It is not easier to use the __construct
, young man?
In your case I would make two modifications: I would add a constructor leaving a default value for the property. And set the property to protected
or privada
so it won’t be externally altered.
class Classe {
protected $valor = 0;
public function __construct(int $valor = 0)
{
$this->valor = $valor;
}
}
Now I believe your doubt is regarding the method Classe::calcula
...
Answer: I do not believe it is advantageous to do this in case of a method that will calculate. If it will calculate, it should return the value, and not change the base value (the property $valor
).
I would leave the method calcula
thus:
public function calcula(): int
{
return $this->valor * 2;
}
Now one thing you should ask yourself is not "whether it is good practice or not", but whether it will be useful or not to modify the value $valor
.
You should think that there are several project standards just to solve common implementation problems (although you shouldn’t stick to that) and that each situation implies a different implementation.
Just out of curiosity, a form that could be applied in the above case (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 that case I would modify the method valor
to just return a value.
See 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;
}
}
Use:
$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)
maybe you don’t start
$this->valor
an error occurs, otherwise I believe not. example https://ideone.com/fork/ry4N8r– novic