note 40515 added to function.get-object-vars
| From: | manicdepressiveATmindlessDOTcom at rn2 dot php dot net | Date: | Sat, 06 Mar 2004 00:57:18 +0000 |
| Subject: | note 40515 added to function.get-object-vars | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-66332@lists.php.net to get a copy of this message | ||
more strange, strange behaviour:
if you are trying to deep-copy an object with get_object_vars(), strange behaviour can accidentally
clobber your original object properties. please read very, very carefully:
get_object_vars() may either return references to *or* deep copies of the object's properties
*depending on whether that property has been set with the -> operator*. (this behaviour
probably varies per php platform and os so please confirm for yourself.)
furthermore, consider
$properties = get_object_vars($obj);
normally, unset()ting a reference does not affect the original, i.e. $ref = NULL; is not the same as
unset($ref); per the references documentation. However, if you have this strange references version
and you unset() an array element of $properties, it will *SET THE OBJECT PROPERTY TO NULL*, which is
not how references normally work.
even stranger behaviour comes into effect that i can only express with an example. please test this
with your version and OS and proceed very carefully:
-->
<?php
echo "<pre>\n";
class Lump
{
var $size = 'average';
function & copy()
{ // return a deep copy
$copy = new Lump();
$properties = get_object_vars($this);
foreach( array_keys( $properties ) as $property ){
$copy->$property = $properties[$property]; // deep, right?
}
return $copy;
}
}
$lump = new Lump();
$lump->size = 'huge'; // <--- this line changes everything
// comment above line out, and see the difference
// also, try substituting another property for 'size'
$properties = get_object_vars($lump);
$properties['size'] = 'small'; // this behavior varies
echo "after changing the properties array:\n";
var_dump( $lump );
// it's either big or small (never huge) depending on
// whether you commented-out the indicated line
//------------- let's try using our copy() method
$original_lump = new Lump();
$original_lump->size = 'huge'; // this line changes the behaviour
$other_lump =& $original_lump->copy();
unset( $other_lump->size );
echo "after unsetting in copy:\n";
var_dump( $original_lump ); // i'm afraid so -- original value clobbered !
echo "</pre>\n";
?>
code till dawn,
mark meves
----
Manual Page -- http://www.php.net/manual/en/function.get-object-vars.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+40515
Delete -- http://master.php.net/manage/user-notes.php?action=delete+40515&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+40515&report=yes
Search -- http://master.php.net/manage/user-notes.php