2013-11-21 82 views
0

這是一些代碼。我把它從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">&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(); 
?> 
+3

創建構造函數因爲要在初始化類實例化的東西。與其他語言相反,在PHP中它不是強制性的 –

+0

這確實是一個無用的構造函數。但有時他們不是 – Nanne

回答

1

將字符串連接到您的page實例var。在構造函數中,您將其設置爲空字符串。如果您刪除構造函數$this->pageNULL 但仍然

NULL."some string"也適用於PHP。 這就是爲什麼你會得到相同的結果。

TL; DR

您的特定構造函數是無用的。

0

我不完全明白你的意思,但對我的理解構造函數是創建類。但是你不需要每次都創建構造函數,因爲它具有默認值。 當您創建新類時,默認構造函數是空白構造函數(不包含參數)

但是,如果您想要創建包含參數的類,例如您希望使由URL啓動的網頁類成爲可能,這樣

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

像這樣的事情

相關問題