Making a Copy of an Object in PHP

Posted in Code, Tips and Tricks

In PHP4 objects were passed by value, it’s probably the intuitive way to deal with variables for a beginner and in a language where objects are not first class. However in PHP5 this has been changed and now objects are passed by reference, this stung me when writing some tests recently.

public function testNameIsUnique() {
	$test1 = $this->BuildValidDiscountType();
	$test2 = $test1;

	$test1->Save();
	$this->assertTrue($test1->id > 0);

	$this->setExpectedException('DiscountTypeException');
	$test2->Save();
}

This code shouldn’t have worked as far as I was concerned, in fact I was expecting an exception to be raised. Instead it was working and after a little debug tour I found that my $test1 = $test2 line was causing $test2 to be a reference to $test1, not what I wanted. This caused my update method to be triggered instead and of course the name is still unique.

It only required a small change to that line, using the clone specifier :

$test1 = clone $test2;

After that everything went as expected and I knocked off another test, and added to my PHP knowledge.

No Comments

No comments have been left yet, be the first.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Twitter

The latest @rubyfive podcast is up, our own @sj26 receiving a mention for Ruby 1.9.3 performance improvements. http://t.co/hfx3EPMz

@frontiergroup about 4 days ago #

Search Posts

Featured Posts

Categories

Archives

View more archives