Making a Copy of an Object in PHP

February 5th, 2009, by Aaron

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.

We are a Perth web design and web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. Jump to the Ruby on Rails category or contact us.

Leave a Reply


Follow Us

Stay in the Loop

  • Enter your email address to subscribe to our mailing list. You'll get updates about our products, specials and bonus offers, and general behind the scenes news from our team.

Twitter

Facebook Fans

Newsletters

Testimonial

The boys at The Frontier Group are amazing! For such a relaxed and personable organisation, they have phenomenal technical ability and a rampant professionalism. They have customisable solutions for all of my IT needs and they always deliver, on time and beyond expectation.

They fix problems other service providers can't and they helped me get a critical section of my web site up and running 10 minutes after I emailed the request!

Alex Hyndman, Nexus Car Share.

Featured Project

Case Study - Caudo Group - www.caudo.com.au

Website

www.caudo.com.au

Caudo Machinery

Caudo Group engaged our services to redesign their outdated website. We sent our photographer on-site to capture the essence of their business and turned it into a stunning web design.