다음은 몇 가지 코드입니다. 나는 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">© $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