note 109737 added to language.oop5.references
| From: | JonWhitener | Date: | Wed, 15 Aug 2012 13:55:29 +0000 |
| Subject: | note 109737 added to language.oop5.references | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-190087@lists.php.net to get a copy of this message | ||
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
----
Server IP: 69.147.83.197
Probable Submitter: 198.109.51.204
----
Manual Page -- http://www.php.net/manual/en/language.oop5.references.php
Edit -- https://master.php.net/note/edit/109737
Del: integrated -- https://master.php.net/note/delete/109737/integrated
Del: useless -- https://master.php.net/note/delete/109737/useless
Del: bad code -- https://master.php.net/note/delete/109737/bad+code
Del: spam -- https://master.php.net/note/delete/109737/spam
Del: non-english -- https://master.php.net/note/delete/109737/non-english
Del: in docs -- https://master.php.net/note/delete/109737/in+docs
Del: other reasons-- https://master.php.net/note/delete/109737
Reject -- https://master.php.net/note/reject/109737
Search -- https://master.php.net/manage/user-notes.php