一千萬個為什麽

搜索

在運行時更改對象的類

我正在使用一個CMS,Joomla,並且有一個核心類將一組參數呈現給一個表單JParameter。基本上它有一個 render()函數,用於輸出一些與表格相關的HTML,這與我的網站其余部分不一致。

對於可維護性問題,並且因為我不知道在何處使用它,我不想更改核心代碼。最理想的是能夠定義一個擴展JParameter的新類,然後將我的$ params對象放到這個新的子類中。

// existing code --------------------
class JParameter {
    function render() {
       //return HTML with tables
    }
   //of course, there's a lot more functions here
}

// my magical class -----------------
class MyParameter extends JParameter {
    function render() {
       //return HTML which doesn't suck
    }
}

// my code --------------------------
$this->params->render();   //returns tables
$this->params = (MyParameter) $this->params; //miracle occurs here?
$this->params->render();   //returns nice html

最佳答案

There's always PECL's Classkit but I get a feeling that you'd really rather not do this. Assuming you're directly calling $this->params->render(), you might just want to make a function/object that does an alternate rendering ( MyParamRenderer::render($this->params)) and avoid performing OO gymnastics not natively supported by the language.

轉載註明原文: 在運行時更改對象的類