這是一些代碼。我把它從PHP文集第1部分。這是PHP 4的代碼,所以使用類名構造函數。爲什麼在php4或php 5中使用構造函數?
爲了實驗我刪除了構造函數,但它返回了相同的結果。 那麼,爲什麼我使用構造函數,如果我得到相同的結果沒有它? 對不起,我的英文。
<?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();
?>
創建構造函數因爲要在初始化類實例化的東西。與其他語言相反,在PHP中它不是強制性的 –
這確實是一個無用的構造函數。但有時他們不是 – Nanne