Constructors and destructors in PHP4

Object oriented programming has been part of PHP scripting language for a while. The latest major release PHP5 introduces complete collection of object oriented programming tools. Along with classes and inheritance the new version also gives such rich features like abstract classes, interfaces, exceptions and many more. Many programmers still use the older release PHP4 for various reasons. Web hosting services offer version 4 because so much has been coded for this very popular release and migrating to the newer one would be unrealistic in some cases. Now that PHP5 has wide range of OO capabilities one would like to enhance PHP4 in case of later upgrading. PHP5 introduces new concept for class constructors as well as a whole new idea of destructors. In PHP4 the class constructor was simply a function with the same name like in Java programming language.

// PHP4 class MyClass { function MyClass() { } } // PHP5 class MyClass { function __constructor() { } function __destructor() { } }

While PHP4 lacks destructor, one can easily emulate both the new __constructor() and __destructor() functions using a little trick found in language repertoire. The following code snippet shows how to imitate PHP5-like constructors and destructors.

// PHP4 class MyClass { function MyClass() { // original class constructor $args = func_get_args(); call_user_func_array(array(&$this, ’__construct’), $args); register_shutdown_function(&$this, ’__destruct’)); } function __construct() { // constructor code goes here } function __destruct() { // constructor code goes here } }

Final words

Object oriented programming substantially simplifies application structures. Encapsulating program logic in classes makes the application structural and extremely easy to maintain. Unfortunately PHP4 offers only limited range of tools for OO programming. Moving to lot more object-friendly PHP is encouraged, but not always possible. While waiting hosting services to upgrade programmers may start shifting their code towards PHP5 by emulating new features with old tricks.

Julkaistu sunnuntaina 5.10.2008 klo 8:42 avainsanoilla harrastukset ja Internet.

Yleisönä Uutisvuodossa
Vaalikarkkia ja silakoita
Evästeiden käyttö

Käytän sivustollani evästeitä tarjotakseni parhaimman mahdollisen lukukokemuksen blogini lukijoille. Jos jatkat sivustoni käyttöä, oletan, että hyväksyt evästeiden käytön sivustollani.

Lisätietoja evästeiden käytöstä