doutan8506 2013-11-21 13:38
浏览 21

为什么在php4或php 5中使用构造函数?

Here is some code. I took it from php anthology part1 . It's php 4 code so construct function using the class name.

To experiment I remove construct function and yet it returned same result. So why do I use construct function if I get same result without it? Sorry for my English.

<?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>
");
// Add the footer to the page
$webPage->addFooter(date('Y'), 'Object Designs Inc.');
// Display the page
echo $webPage->get();
?>
  • 写回答

2条回答 默认 最新

  • dongzan0108 2013-11-21 13:41
    关注

    You concatenate Strings to your page instance var. In the constructor you set it to be an empty string. If you remove the constructor $this->page is NULL But still

    NULL."some string" also works in php. That´s why you get the same result.

    TL;DR

    Your particular constructor is useless.

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源