0

I am using the following code:

$input = new DateTime(filter_input(INPUT_GET, 'date'));
$input->modify('midnight');

echo $input->format(DateTime::RFC3339) . "\n";

$end = $input;
$end->modify('+3 hours');
echo $input->format(DateTime::RFC3339) . "\n";
echo $end->format(DateTime::RFC3339) . "\n";

Which is giving the following output:

2016-02-01T00:00:00-5:00
2016-02-01T03:00:00-5:00
2016-02-01T03:00:00-5:00

Shouldn't the output on line two be the same as the first?

From what I understand to assign a variable by reference you need to use $a = &$b, so what I am using ($a = $b) should be by value. So an function called on $end should not modify $input as well, correct? What am I missing?

Bryan
  • 14,756
  • 10
  • 70
  • 125
  • 3
    Don't confuse scalar variables with object instances..... instances are always a pointer – Mark Baker Feb 01 '16 at 14:37
  • 2
    From the [PHP Docs](http://nl1.php.net/manual/en/language.oop5.basic.php) - `When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.` – Mark Baker Feb 01 '16 at 14:39

1 Answers1

3

Problem is that DateTime is object and objects is assigned always by reference. If you want assign by "value", you must use cloning like $end = clone $input;.

Here is information about it in PHP manual: http://php.net/manual/en/language.oop5.references.php

tomas.lang
  • 489
  • 3
  • 10
  • This may be worth a read too: http://stackoverflow.com/questions/16893949/php-object-assignment-vs-cloning – Tobias Xy Feb 01 '16 at 14:41
  • Okay, did not know that, thank you. As a side note, would you happen to know why this is? It just seems counter-intuitive to me, especially considering normal variables are assigned by value, unless otherwise specified. – Bryan Feb 01 '16 at 14:44
  • This is because objects is represented only by reference to memory instead of scalars which is represented by own value, like Mark Baker mentioned. – tomas.lang Feb 01 '16 at 14:48