<?php
class Model
{
private $title = "Please define page's title";
private $body = "Please define page's body";
private $footer = "Please define page's footer";
public function setTitle($title)
{
$this->title = $title;
}
public function setContent($content)
{
$this->body = $content;
}
public function setFooter($footer)
{
$this->footer = $footer;
}
public function showTitle()
{
return $this->title;
}
public function showContent()
{
return $this->body;
}
public function showFooter()
{
return $this->footer;
}
}
class WebPage extends Model
{
function __construct()
{
echo '<html>';
echo '<head>';
echo '<title>';
echo $this->showTitle();
echo '</title>';
echo '</head>';
echo '<body>';
echo $this->showContent();
echo $this->showFooter();
echo '</body>';
echo '</html>';
}
}
?>
//In the indeex file
<?php
$model = new Model();
$model->setTitle("Php OOP Test");
$model->setContent("HelloWorld");
$model->setFooter("Hello");
$page = new WebPage();
?>
问题在于标题,内容和页脚都没有改变。
我尝试构建自己的PHP框架。
这看起来有点愚蠢,但我对这种事情不熟悉。
答案 0 :(得分:1)
这就是你要做的,你想做什么
class Model
{
private $title = "Please define page's title";
private $body = "Please define page's body";
private $footer = "Please define page's footer";
public function setTitle($title)
{
$this->title = $title;
}
public function setContent($content)
{
$this->body = $content;
}
public function setFooter($footer)
{
$this->footer = $footer;
}
public function showTitle()
{
return $this->title;
}
public function showContent()
{
return $this->body;
}
public function showFooter()
{
return $this->footer;
}
}
class WebPage extends Model
{
public function output() {
echo '<html>';
echo '<head>';
echo '<title>';
echo $this->showTitle();
echo '</title>';
echo '</head>';
echo '<body>';
echo $this->showContent();
echo $this->showFooter();
echo '</body>';
echo '</html>';
}
}
$page = new WebPage();
$page->setTitle("Php OOP Test");
$page->setContent("HelloWorld");
$page->setFooter("Hello");
$page->output();
如评论中所述,您在实例中实例化了两个不同类的两个独立实例。由于WebPage
正在扩展Model
,因此您只需要一个WebPage
实例。从那里,我将回声内容移动到Webpage
的单独公共方法中,以便在修改Model
属性后调用它
答案 1 :(得分:0)
您正在创建页面的新对象,该对象是$page = new WebPage();
模型的子项,因此您将为新对象创建此变量
private $title = "Please define page's title";
private $body = "Please define page's body";
private $footer = "Please define page's footer";
在另一个$ model
对象上设置标题和内容等变量答案 2 :(得分:0)
这是正确的实施。
由于WebPage
扩展Model
继承了其所有函数和变量,因此我们创建了WebPage
的新实例,然后设置title
,{{1} },body
与此对象。然后我们调用特定于footer
类的showPage
,它将输出我们设置的所有变量。
WebPage