【问题标题】:PHP: Trigger a Method and ignore the returning contentPHP:触发一个方法并忽略返回的内容
【发布时间】:2015-03-11 09:46:39
【问题描述】:

我在 Stackoverflow 上的第一个问题!

首先:感谢您的帮助,并为我的英语不好感到抱歉。 ^^

我尝试获取子类方法赋予其父类方法的值。问题是, 父类方法用exit; 终止当前脚本 + 我无权访问 子类 + 我不想编辑“一个类”(见下文)。

代码,为了更好的理解:

<?php
    // The Controller
    class one{
        // [...]
        public $classVAR = "";
        public $classVAR2 = "";

        public function render($param1, $param2){
            // This are the variables that I need.
            $this->classVAR = $param1;
            $this->classVAR2 = $param2;

            return new View(); // Returns the Page Content
        }

        public function display($param1, $param2, $exit = true){
            echo $this->render($param1, $param2);

            if($exit === true){
                exit;
            }
        }
        // [...]
    }

    // Another Class to which I have no control (ex. "Plugin Classes")
    class two extends one{
        // [...]
        public function index(){
            // Some other Stuff

            //  string  $stuff
            //  array   $otherstuff
            $this->display($stuff, $otherstuff);
        }
        // [...]
    }
?>

尝试 1 :: 使用 ReflectionClass

我试图读取索引方法的内容,在“二类”里面。

所以我抓住了索引函数的来源,并在里面分离了参数 $this-&gt;display 方法调用。

问题:$otherstuff 变量包含 - 在大多数情况下 - 包含一个(或多个)的数组 “key=>option”对,可以被 View Class 使用。还有我用来做这个的“二等舱” 实验,包含'something' =&gt; $this-&gt;loadOptions()这对,并且这个方法被保护了。

尝试 2 :: 使用 ob_start()

我尝试在缓冲区中加载从视图类返回的内容。但是exit; 命令 完全破坏 php 代码并直接打印输出(我不希望从 “查看”类)。

代码:

class myclass extends one{
    public function myfunc(){
        ob_start();
            $something = new two();
            $something->index();
        ob_end_clean();

        $param1 = $this->classVAR;
        $param2 = $this->classVAR2;
    }
}

想法

是否可以临时调用(“二类”的)索引方法,而无需完全中断 通过exit; 行?

或者是否可以在缓冲区中加载“二”类,然后操作$this-&gt;display 方法?如果是,那么我可以添加第三个参数,这将禁用 exit; 行。

或者是否可以“改变”两个类的父类?

您还有其他想法吗,我该如何解决这个问题?但请不要实验性的 PHP 代码, 或其他 PHP 扩展/库。

谢谢! (我希望我能很好地解释我的问题。)

此致, 山姆。

【问题讨论】:

    标签: php class oop exit ob-start


    【解决方案1】:

    您是否尝试将 $exit 的默认值设置为 false ?

    class one{
        //...
    
         public function display($param1, $param2, $exit = false){
            // ...
        }
    }
    

    怎么样 - 第二个选项?

    自定义类扩展了两个类

    class myclass extends two{
    
        public function display($param1, $param2, $exit = false){
            parent::display($param1, $param2, $exit);
        }
    }
    
    $something = new myclass();
    $something->index();
    

    【讨论】:

    • 是的,但我不想编辑一个类。该项目是 CMS 的插件,“一个类”是其中的一部分。我不希望这个插件的用户需要修改系统类。谢谢你的回答。
    • 谢谢! 效果很好!我会赞成你的评论,但我没有足够的声誉,对不起。 ^^ 但是,谢谢!
    • 没有问题...也许以后;)
    • 2 年后......我得到了足够的分数来支持你的评论! xD
    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多