簡體   English   中英

我可以有條件地向我的班級添加函數嗎?

[英]Can I Conditionally add a function to my class?

在框架問題2的答案中,主題是基本主題qa_html_theme_base的擴展。 在此示例中,我擴展了輸出html的html函數。

class qa_html_theme extends qa_html_theme_base
    {
        function html(){
           //Theme goes here   
        }
    }

我希望能夠快速打開和關閉主題以進行測試。 我可以有條件地擴展一堂課嗎

class qa_html_theme extends qa_html_theme_base
    {
        if($debug){
            function html(){}
        }
    }

但這沒有用。

我不確定這是不可能的,在類聲明中的這種語法是不正確的。 如果是這樣,我不確定是否會推薦。

但是,如果您的函數要覆蓋擴展類函數之一,則可以執行以下操作:

class qa_html_theme extends qa_html_theme_base
{
    function html(){
        global $debug; // added to maintain a correct syntax, but you could as well use $this->debug below, if the value comes from a class property.
        if( $debug ){
            // your debug code here
        }
        else {
            parent::html();
        } 
    }
}

我想到做您建議的唯一方法(最好是笨拙的)是有條件地包含類文件。 因此,創建兩個類文件。 我們將調用第一個theme_html.php ,其中包括您的html()函數。 第二個是theme_no_html.php ,它沒有html()函數。 這很麻煩,因為您將需要維護兩個文件。

那我們做

if($debug) {
     include('theme_html.php');
} else {
     include('theme_no_html.php');
}
$class = new qa_html_theme();

如果我的想法是對的,

class qa_html_theme extends qa_html_theme_base
{
    protected $debug = 1; // or const DEBUG = 1;

    /**
     * Constructor
    */
    public function __construct()
    {
        if($this->debug){
            $this->html();
        }else{
          // do anything you want
        }
    }

    protected function html(){
       //Theme goes here   
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM