Future proof PHP class constructer compatible with php4 and higher

Since there was no real viable reference to either confirm or oppose my methods, I figured this may help someone else that is trying to make sure they don’t have to change their code based on the installed PHP version.

As most of us already know, initializing a new class object in PHP4 required the constructor to have the same name as the class.

class Myclass {
 function Myclass()
 {
  echo 'Myclass initialized';
 }
}

Then __construct() was introduced in PHP5.

class Myclass {
 function __construct()
 {
  echo 'Myclass initialized';
 }
}

Now you may be thinking “I’ll just use this from now on”. I however have to write for multiple versions of PHP4/5 and must keep backwards compatibility in mind (at least for now). Here is what I use to make sure it works on all versions of PHP that currently support object-oriented programming or OOP. Anything earlier than PHP4 and I simply tell the client to find a new host, lol.

class Myclass {
 function __construct()
 {
  $this->Myclass();
 }
 function Myclass()
 {
  echo 'Myclass initialized';
 }
}

This method ensures that the class will be constructed properly in both PHP4 and PHP5. Barring any significant changes in PHP6, it should continue to work with that version as well.

Feel free to comment 🙂

Leave a Reply

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