The idea is to write object-oriented programs that will behave the same way in both PHP4 and PHP5. Obviously, the drawback of doing so is that you cannot take advantage of PHP5-only features, such as object destructor methods. But if you accept the limitations, you can still write code for PHP4 that works on PHP5, but there are a few important snags. PHP5’s treatment of objects and references is one of those snags.
In PHP4, you can create a copy of an object using the equals (=) operator alone. However, in PHP5 this will create another reference to the same object (much like Java). PHP5 defines the clone keyword, which can be used to create a separate copy of an object.
PHP5’s clone is, strictly speaking, not a function. It is a language construct, and (in common with some other language constructs such as exit and include) it can be used either with or without parentheses. If we’re going to emulate it in PHP using a function, we will always need to use it with parentheses.
Steven’s method defines “clone” as a function when using PHP4, but still allows PHP5’s built in clone to be used when running in PHP5.
A weakness in his method is its dependance on eval, which I consider to be an inelegant solution (see Lachlan’s rant about eval). Here, eval is used to prevent the function from being defined when using PHP5 (it is a reserved word in PHP5).
If you really don’t care for eval, a possible solution would be to use a conditional include. Place the function definition for clone in a separate file, php4.inc.php, and include that file only when PHP5 is not being used.
The following code, therefore, should provide a PHP4 emulation of PHP5’s clone without using eval:
// Define a PHP4 emulation of PHP5's clone
if (version_compare(phpversion(), '5.0')
What if you don't want to clone an object? If you've done any OOP in PHP4, then you will be familiar with the use of the reference operator & to pass a reference to an object. The good news is that in PHP5, this will continue to work.
On another note, we've had a lot of feedback from you on what's keeping you from moving completely to PHP5. Various issues include web hosts not wanting to make the move, the break in compatibility (particularly the clone issue discussed in this article), and stability issues, while other users report that they are happily using PHP5 exclusively and haven't looked back.