为什么在php4或php 5中使用构造函数?

Here is some code. I took it from php anthology part1 . It's php 4 code so construct function using the class name.

To experiment I remove construct function and yet it returned same result. So why do I use construct function if I get same result without it? Sorry for my English.

<?php
// Page class
class Page {
  // Declare a class member variable
  var $page;
  // The constructor function
  function Page()
  {
    $this->page = '';
  }

  // Generates the top of the page
  function addHeader($title)
  {
    $this->page .= <<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1 align="center">$title</h1>
EOD;
  }
  // Adds some more text to the page
  function addContent($content)
  {
    $this->page .= $content;
  }

  // Generates the bottom of the page
  function addFooter($year, $copyright)
  {
    $this->page .= <<<EOD
            <div align="center">&copy; $year $copyright</div>
</body>
</html>
EOD;
  }

  // Gets the contents of the page
  function get()
  {
    return $this->page;
  }
}// END OF CLASS


// Instantiate the Page class
$webPage = new Page();
// Add the header to the page
$webPage->addHeader('A Page Built with an Object');
// Add something to the body of the page
$webPage->addContent("<p align=\"center\">This page was " .
  "generated using an object</p>
");
// Add the footer to the page
$webPage->addFooter(date('Y'), 'Object Designs Inc.');
// Display the page
echo $webPage->get();
?>

You concatenate Strings to your page instance var. In the constructor you set it to be an empty string. If you remove the constructor $this->page is NULL But still

NULL."some string" also works in php. That´s why you get the same result.

TL;DR

Your particular constructor is useless.

I don't exactly understand what you meant but for my understanding the constructor function is for creating the class. But you don't need to create constructor every time because it has default value. When you create new class the default constructor is the blank constructor (Doesn't contain parameter)

But if you want to create the class that contain parameter such as you want to make webpage class that initiate by URL so you might create constructor like this

      class Page {
      // Declare a class member variable
      var $page;
      // The constructor function
         function Page($url)
      {
        ......
      }
    }

Something like this