我有一个抽象页面类,如下所示:
abstract class Page {
public static function display() {
self::displayHeader();
self::displayContent();
self::displayFooter();
}
public static function displayContent() {
print "<p>some content</p>";
}
public static function displayHeader() {
include_once(kContent . "HeaderContent.class.php");
HeaderContent::display();
}
public static function displayFooter() {
include_once(kContent . "FooterContent.class.php");
FooterContent::display();
}
};
我想从此继承,并且只重写 displayContent 方法,因此页眉和页脚会自动显示,但仍然可以选择重写显示方法,例如对于 .js 文件。
现在我有另一个课程,如下所示:
class FooPage extends Page {
public static function displayContent() {
print "<p>Foo page</p>";
};
现在,不再调用 FooPage 的displayContent
方法,它只是调用超类中的方法。
为什么?我能做些什么?
EDIT
我正在运行 PHP 5.2.17
Ilija,PHP 后期静态绑定“这就是为什么您可能会遇到FooPage::displayContent
不被调用。如果您运行的是 PHP 5.2,那么没有什么可做的(除了使用 debug_backtrace() 的一些技巧 http://www.php.net/manual/en/language.oop5.late-static-bindings.php#101077,老实说我不会推荐这种情况)。
现在,真正引起我注意的是你的方法都是静态的;是否有一个原因?为什么它们不是实例方法?我期望类似的东西:
include_once(kContent . "HeaderContent.class.php");
include_once(kContent . "HeaderContent.class.php");
abstract class Page
{
protected $header;
protected $footer;
public function __construct()
{
$this->header = new HeaderContent();
$this->footer = new FooterContent();
}
public function display()
{
$this->displayHeader();
$this->displayContent();
$this->displayFooter();
}
public function displayContent()
{
print "<p>some content</p>";
}
public function displayHeader()
{
$this->header->display();
}
public function displayFooter()
{
$this->footer->display();
}
};
class FooPage extends Page
{
public function displayContent()
{
print "<p>Foo page</p>";
}
}
然后在你看来你会写这样的东西:
$page = new FooPage();
$page->display();
需要考虑的一些事项:
- 生成视图内容时通常最好不要使用 print/echo。相反,尝试创建字符串并执行打印/回显作为最后一步。这使得以后编写测试变得更容易。
Example:
public function display()
{
return
$this->displayHeader() .
$this->displayContent() .
$this->displayFooter();
}
public function displayContent()
{
return "<p>some content</p>";
}
public function displayHeader()
{
return $this->header->display();
}
....
$page = new FooPage();
echo $page->display();
- 如果您需要随着应用程序的增长而执行此操作,则可以将页眉和页脚作为 Page 构造函数参数传递。只要它们是理解 display() 消息的对象(即多态性 http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming)事情应该没问题。
HTH
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)