erajuan
erajuan

Reputation: 2294

Carbon: error to create date , change date affect all variables

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

enter image description here

Where is the problem?

Upvotes: 0

Views: 147

Answers (3)

user2094178
user2094178

Reputation: 9464

You should change to the following:

$fin = $inicio->copy();
$otro = $fin->copy()->addHours(1);

Upvotes: 0

Yehia Awad
Yehia Awad

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

ksimka
ksimka

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

Related Questions