2013-11-21 3 views
0

다음은 몇 가지 코드입니다. 나는 php anthology part1에서 가져 갔다. 그것은 PHP 4 코드이므로 클래스 이름을 사용하여 함수를 구성하십시오.php4 또는 php 5에서 construct 함수를 사용하는 이유는 무엇입니까?

실험하려면 구조 함수를 제거했지만 동일한 결과를 반환했습니다. 그렇다면 왜 그것없이 동일한 결과를 얻으면 구조 함수를 사용해야합니까? 영어로 죄송합니다.

<?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

등이

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

뭔가처럼 생성자를 만듭니다. 다른 언어와 달리 PHP에서는 필수가 아닙니다. –

+0

이것은 실제로 쓸모없는 생성자입니다. 그러나 때때로 그들은 그렇지 않습니다. – Nanne

답변

1

문자열을 page 인스턴스 var에 연결합니다. 생성자에서 빈 문자열로 설정합니다. 생성자를 제거하면 $this->pageNULL 이지만 여전히

NULL."some string"도 PHP에서 작동합니다. 그것이 동일한 결과를 얻는 이유입니다.

TL

귀하의 특정 생성자는 쓸모가 없습니다.

0

나는 당신이 무엇을 의미하는지 정확히 이해하지 못한다. 그러나 나는 생성자 함수가 클래스를 생성하기위한 것이라는 것을 나의 이해를 위해 설명했다. 그러나 기본값을 가지기 때문에 매번 생성자를 생성 할 필요가 없습니다. 새 클래스를 만들면 기본 생성자는 빈 생성자입니다 (매개 변수를 포함하지 않음)

URL로 시작하는 웹 페이지 클래스를 만들려는 것처럼 매개 변수를 포함하는 클래스를 만들려면 당신은 클래스 인스턴스에서 뭔가를 초기화 할 때문에이