February 11, 2006

Downgrading from PHP5 to PHP4

One of the projects I'm currently involved in is a web based Prediction Market. For those of you who never heard of the field, run a quick search on in Google or in a Wiki and I'm sure you'll get all the information you need.
It's a very intelligant way to aggregate information and obtain insight on the future.
Alas, since we're not here to talk about business or predicting the future (interesting as that might be.... ) let me get to the point.

During an integration with a client, I discovered that they do not use php5, but rather, an earlier version - PHP4 (v4.3.2 I believe). Obviously I requested that they would upgrade, or at least run their HTTP server (Apache) with support to both versions (it is possible...).
They declined.

As they were a very important client (our first..) I had to undergo the rigorous task of making the code PHP4 compatible. following that I decided to publish a short recipe for the process.

Recipe for Converting PHP5 to PHP4 compatible code:
1. Functions - remove the following keywords: 'public', 'private' and 'static'. There are no visibility modifiers, and all functions can be accessed statically or from an instance.
2. Instance variables - replace 'public' and 'private' with 'var'.
3. Static variables - replace with a getter and setter functions. You can use the following pattern for each variables. (Credit to peter joel, a comment at http://il.php.net/keyword.paamayim-nekudotayim):


class A
{
function getVar($val=NULL)
{
static $class_variable = 0;
if ($val != NULL)
$class_variable = $val;
return $class_variable;
}

function setVar($val=0)
{
return A::getVar($val);
}
}

4. object usage - references in PHP4 is a bit different than it is in PHP5
4.1 - prefix all functions that return an object with an amp '&'
4.2 - when invoking a functi0n that returns an object use $obj = &function() (mind the &)
4.3 - when passing an object, we need to pass it by reference, so prefix the parameter with an &, for example: function func_name(&$param_name)

After applying this recipe, your code should be PHP4 compatible.