Warning: Undefined array key "HTTP_ACCEPT_LANGUAGE" in /customers/9/b/5/fun-tech.se/httpd.www/php_tutorial/class.page.php on line 130 OOP php5 HOWTO - The constructor

The php5 object oriented web design howto - The constructor

__construct and __destruct

Now let's do something fun, let's play with the constructor and destructor. This is two magic functions that is called when a object is created, and when the object is destroyed.

Since the page object is created when you use the keyword new, that is the moment when the function __construct is called. And the magic thing is that this is done in the background, so you don't have to write any code to make this happen.

But that is only half of the fun. When the object is destroyed, normally at the end of the program, the destructor (__destruct) is called. This also happens in the background.

So since the constructor is called in beginning, we can move the code that use to live in function head into the magic function __construct. And since the destructor is called at the end we can move the code from the function foot, into the magic function __destruct. So we end up with something like this.

Filename: class.page.php

<?php
class page
{
    function __construct()
    {
        print "<html>\n";
        print "<body>\n";
    }

    function __destruct()
    {
        print "</body>\n";
        print "</html>\n";
    }
}
?>

Then the caller page would become a little bit smaller.

Filename: p04_ex01.php

<?php
require_once("class.page.php");
$page = new page();
?>

<h1>Hello</h1>
<p>What a nice little page</p>


Notice that we only need the code that creates the object page, and that we don't need to call __construct and __destruct.

The resulting data will look like this, notice the printout from the constructor and destructor is there.

Filename: p04_ex01.out

<html>
<body>

<h1>Hello</h1>
<p>What a nice little page</p>


</body>
</html>