Wednesday, August 24, 2005

PHP 4 constructor and destructor

Here is a way to have constructor and destructor functions in php4:
/*
*
* Because php 4 does not have a proper OOP implementation
* here is a way to have php4 destructor and constructor
*
*/
class demoClass
{
// {{{ constructor
/**
 * php4 class contructor
 *
 * @return object
 */
function demoClass()
{
 //destructor
 register_shutdown_function(array(&$this, '__destruct'));

 //constructor
 $argcv = func_get_args();
 call_user_func_array(array(&$this, '__construct'), $argcv);
}
// }}}

// {{{ __construct()
/*
* constructor function implementation
*/
function __construct()
{
 //code for constructor goes here
}
// }}}

//{{{ __destruct()
/*
* destructor function implementation
*/
function __destruct()
{
 //code for destructor goes here
}
//}}}
}

6 comments:

Anonymous said...

The solution you've posted here, helped me to make my php script (classes developed on php5) compatible with php4. It really works!.

Miguel Angel said...

It's a good idea

Anonymous said...

such amount of stupid comments doesn't make your code better. it makes it hard to read.

Anonymous said...

Works perfect, thx!

Rochak Chauhan said...

Well it is fine for constructor, but I dont think it will work for declaring variables inside a class.

FYI
In PHP4 the syntax is:
var $variable = ""

but in PHP5 the syntax is:

public $variable="";
or
private $variable="";
or
protected $variable="";

Raviraj said...

thanks, works perfectly..