php4, php5, objects and cloning

We take a very simple class:

class Foobar {
var $myvar = 1;

function Foobar() {
}

function printit() {
    echo "var is " . $this->myvar . "n";
}

function incr() {
    $this->myvar += 1;
}

}

$f = new Foobar();
$a = $f;
$b = $f;

$a->printit();
$a->incr();

$b->printit();

And run it with PHP4 and PHP5:

davidw@byron:/tmp$ php4 foobar.php 
var is 1
var is 1
davidw@byron:/tmp$ php5 foobar.php 
var is 1
var is 2

Apparently it’s possible to use the clone function to do what we want with PHP5, but… that means we have to track down every single place in the code where there is something like $foo = $bar. And hope that we got them all, because otherwise subtle bad things might happen. The codebase I’ve inherited isn’t great to begin with, and hunting down every object copy is bound to be torture. Ouch.

Update

It’s been pointed out that my description of exactly what’s happening internally isn’t correct. However, from my point of view, the end result is the same: a massive search and replace operation in order to obtain the “old” behavior by using clone. Most likely, this means that we won’t be able to upgrade soon, which means that we won’t be able to take advantage of some of the nice new PHP5 features, which will slow down other works in progress. For want of a nail…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s