gpt4 book ai didi

php - 覆盖 PHP 中的静态方法

转载 作者:可可西里 更新时间:2023-11-01 13:50:44 25 4
gpt4 key购买 nike

我有一个如下所示的抽象页面类:

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 方法,而是调用父类(super class)中的方法。

为什么?我能做什么?

编辑

我正在运行 PHP 5.2.17

最佳答案

Ilija,PHP < 5.3 没有“Late Static Binding”,这就是您可能遇到 FooPage::displayContent 未被调用的原因。如果您运行的是 PHP 5.2,则没有什么可做的(除了 some hacks using debug_backtrace() ,老实说,我不建议在这种情况下使用它)。

现在,真正引起我注意的是你们的方法都是静态的;是否有一个原因?为什么它们不是实例方法?我希望是这样的:

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>";
}
}

稍后在您的 View 中您将编写如下内容:

$page = new FooPage();
$page->display();

一些需要考虑的事情:

  • 在生成 View 内容时通常最好不要使用 print/echo。相反,尝试创建字符串并将打印/回显作为最后一步。这使得以后编写测试更容易。

例子:

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();
  • 如果随着应用程序的增长需要这样做,您可以将页眉和页脚作为页面构造函数参数传递。只要它们是理解 display() 消息(即 polymorphic )的对象,就应该没问题。

HTH

关于php - 覆盖 PHP 中的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13174343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com