Page 1 of 1
Assigning to $this PHP 5
Posted: Tue Aug 31, 2004 12:22 pm
by raygr
I'm porting some code from PHP 4 to PHP 5. It's not liking this:
$s = _SESSION['x'];
$this = unserialize($s);
The reason I'm doing this is to have a class method called "LoadFromSession". If you have a better way to do this, please tell me.

In general, (in PHP5) I would like to be able to copy over the contents of the current object. Is there a way to assign a new object to the current object (pointed to by $this)? For eg:
$this = $otherobject_of_same_type
Posted: Tue Aug 31, 2004 1:03 pm
by timvw
I think $this is a CONSTANT pointer to the current object. (And thus cannot be changed)
Meaby this works
$instance1 = new Class();
$instance2 = new Class();
$instance1 =& $instance2;
http://be2.php.net/references
Posted: Tue Aug 31, 2004 1:07 pm
by feyd
$foo =& $bar
creates a reference to $bar.. any change to $bar will change $foo, and vice versa.
Posted: Tue Aug 31, 2004 1:11 pm
by markl999
With PHP5 $foo = $bar is ok as it auto assigns by reference rather than creating/copying a new object.
Posted: Tue Aug 31, 2004 1:51 pm
by raygr
markl999 wrote:With PHP5 $foo = $bar is ok as it auto assigns by reference rather than creating/copying a new object.
Right, you need to use the clone keyword to actually copy an object. But, I want a way to copy an object into the current object.
If this were C++, I want to do this:
*this = object;
Posted: Tue Aug 31, 2004 1:59 pm
by feyd
standard internal cloning: copy over each internal variable.
Posted: Tue Aug 31, 2004 5:51 pm
by raygr
feyd wrote:standard internal cloning: copy over each internal variable.
So, there's no way to do it in one assignment? I have to assign to each member variable?
Posted: Tue Aug 31, 2004 5:56 pm
by markl999
Right, you need to use the clone keyword to actually copy an object. But, I want a way to copy an object into the current object.
If this were C++, I want to do this:
*this = object;
I'm a bit confused as to why you'd want to copy an object into an existing object, this would in effect overwrite it, so why not just use __clone to copy the object into a variable hence creating a copy of the object. I'm not sure why you need an existing object to copy into ?
I suppose the real question is, when do you ever need a copy of an object?