0

这是一些代码。我从 php 选集第 1 部分中获取它。它是 php 4 代码,所以使用类名构造函数。

为了进行实验,我删除了构造函数,但它返回了相同的结果。那么,如果没有构造函数我得到相同的结果,为什么还要使用它呢?对不起我的英语不好。

<?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>\n");
// Add the footer to the page
$webPage->addFooter(date('Y'), 'Object Designs Inc.');
// Display the page
echo $webPage->get();
?>
4

2 回答 2

1

您将字符串连接到您的page实例变量。在构造函数中,您将其设置为空字符串。如果你删除构造函数$this->pageNULL 但仍然

NULL."some string"也适用于 php。这就是为什么你会得到相同的结果。

TL;博士

您的特定构造函数没用。

于 2013-11-21T13:41:08.513 回答
0

我不完全理解您的意思,但据我了解,构造函数用于创建类。但是您不需要每次都创建构造函数,因为它具有默认值。创建新类时,默认构造函数是空白构造函数(不包含参数)

但是,如果您想创建包含参数的类,例如您想制作由 URL 启动的网页类,那么您可以创建这样的构造函数

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

像这样的东西

于 2013-11-21T13:55:54.337 回答