PHP 8.5.0 Beta 1 available for testing

Voting

: six minus five?
(Example: nine)

The Note You're Voting On

Jon Whitener
12 years ago
The use of clone may get you the behavior you expect when passing an object to a function, as shown below using DateTime objects as examples.

<?php
date_default_timezone_set
( "America/Detroit" );

$a = new DateTime;
echo
"a = " . $a->format('Y-m-j') . "\n";

// This might not give what you expect...
$b = upDate( $a ); // a and b both updated
echo "a = " . $a->format('Y-m-j') . ", b = " . $b->format('Y-m-j') . "\n";
$a->modify( "+ 1 day" ); // a and b both modified
echo "a = " . $a->format('Y-m-j') . ", b = " . $b->format('Y-m-j') . "\n";

// This might be what you want...
$c = upDateClone( $a ); // only c updated, a left alone
echo "a = " . $a->format('Y-m-j') . ", c = " . $c->format('Y-m-j') . "\n";

function
upDate( $datetime ) {
$datetime->modify( "+ 1 day" );
return
$datetime;
}

function
upDateClone( $datetime ) {
$dt = clone $datetime;
$dt->modify( "+ 1 day" );
return
$dt;
}
?>

The above would output something like:

a = 2012-08-15
a = 2012-08-16, b = 2012-08-16
a = 2012-08-17, b = 2012-08-17
a = 2012-08-17, c = 2012-08-18

<< Back to user notes page

To Top