0
これは何度も尋ねられた質問ですが、答えはここには当てはまりません。親関数をオーバーライドする
私は、次のPageBase
クラスを持っている:
<?php
class PageBase {
public $templatefile = '404';
function Before() {}
function After() {}
function Display() {
$smarty = System::GetSmarty();
$smarty->display('views/'.$this->templatefile.'.tpl');
}
function Run() {
self::Before();
self::Display();
self::After();
}
}
すべてこのクラスは私の他のページのための基盤を提供している行うことを意図しています。これらのページには、ページを表示する前/後に独自のコードを実行する必要がある場合とそうでない場合があり、通常は独自の$templatefile
があります。たとえば、私のHome
クラスです。
<?php
class Home extends PageBase {
public $templatefile = 'home';
function Before() {
var_dump($_REQUEST);
}
function After() {}
}
私はに実行している問題は、正しいテンプレートファイル(home
)がロードされているが、Home::Before()
のコードはPageBase::Before()
が代わりに実行され、$home->Before()
インスタンス化を駆け抜けていないことです。
これに取り組む正しい方法は何ですか? PHPは、親の関数をオーバーライドする方法を提供していますか?
<?php
Interface PageBase {
public function Before();
public function After();
public function Display();
public function Run();
}
class Page Implements PageBase {
public $templatefile = '404';
function Before() {}
function After() {}
public function Set($page) {
if (class_exists($page)) {
$class = new $page($page);
return $class;
}
return false;
}
function Display()
{
$smarty = System::GetSmarty();
$smarty->display('views/' . $this->templatefile . '.tpl');
}
function Run()
{
self::Before();
self::Display();
self::After();
}
}
class Home extends Page Implements PageBase
{
public $templatefile = 'home';
function After() { parent::After(); }
function Display() { parent::Display(); }
function Run() { parent::Run(); }
function Before() {
var_dump($_SERVER);
}
}
$Page = new Page(); //Create a new page instance for all of the functionality
$home = $Page->Set("Home"); //Returns a new class of Home
$home->Display(); //Displays the templatefile "home"
私はこれが役に立てば幸い:
種類は、私は均一性のためのインターフェイスを使用して変数が設定されていたらそうのように、親を呼ぶような、個人的に
[Late Static Binding](http://php.net/manual/en/language.oop5.late-static-bindings.php)を参照してください。または、より良い、静的を使用しないでください。すなわち、self :: Before();の代わりに '$ this-> Before();'を使います。 –
@AlexHowanskyありがとう、どうやってそれを逃したのかわからない、それを修正! – Ieuan