0

ここにいくつかのコードがあります。php アンソロジー part1 から取ってきました。これは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

0

私はあなたが何を意味するのか正確には理解していませんが、私の理解では、コンストラクター関数はクラスを作成するためのものです。ただし、コンストラクターにはデフォルト値があるため、毎回コンストラクターを作成する必要はありません。新しいクラスを作成するとき、デフォルトのコンストラクターは空のコンストラクターです (パラメーターを含まない)

ただし、URL で開始する Web ページ クラスを作成するなどのパラメーターを含むクラスを作成する場合は、このようなコンストラクターを作成できます。

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

このようなもの

于 2013-11-21T13:55:54.337 に答える