Reputation: 2294
Why change all variables.
how to avoid my variables do not change its value
In my controller
public function show()
{
$inicio = Carbon::createFromFormat('Y-m-d H:i:s',"2016-02-04 11:00:00");
$fin = $inicio;
$otro = $fin->addHours(1);
return view('horas',array('inicio'=>$inicio,'otro'=>$otro,'fin'=>$fin));
}
My views:
<p><b>Inicio: </b> {{$inicio}}</p>
<p><b>Fin: </b> {{$fin}}</p>
<p><b>Otro: </b> {{$otro}}</p>
The result
Where is the problem?
Upvotes: 0
Views: 147
Reputation: 9464
You should change to the following:
$fin = $inicio->copy();
$otro = $fin->copy()->addHours(1);
Upvotes: 0
Reputation: 2978
When you are making $fin=$inicio;
$fin
will always have a reference to $inicio
which means that if $inicio
changes $fin
will simultaneously change, this is how objects work this is object oriented world.
Try this instead:
public function show()
{
$inicio = Carbon::createFromFormat('Y-m-d H:i:s',"2016-02-04 11:00:00");
$fin = clone $inicio;
$otro = clone $fin->addHours(1);
return view('horas',array('inicio'=>$inicio,'otro'=>$otro,'fin'=>$fin));
}
Upvotes: 1
Reputation: 1455
It's because Carbon objects are mutable.
Try to clone them.
public function show()
{
$inicio = Carbon::createFromFormat('Y-m-d H:i:s',"2016-02-04 11:00:00");
$fin = clone $inicio;
$otro = clone $inicio; // not sure why you need this
$fin->addHours(1);
return view('horas',array('inicio'=>$inicio,'otro'=>$otro,'fin'=>$fin));
}
Upvotes: 1