这是一些代码。我从 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">© $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();
?>