繁体   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