duanmao9918 2013-02-01 15:10
浏览 37
已采纳

如何在php中将变量传递给我的视图

I have a class which contains a method to load a view. This works perfect and the page is loaded correctly! The problem I'm having is that I can't seem to figure out a way to pass variables to the view that my method currently tries to load. How can I go by passing variables to the page? Is there a way I can manipulate my current code to make this work? Or am I going in the complete opposite direction?

Controller Class:

<?php
    class Controller {

        private $args = array();

        public function view($page, $args = null) {

            if ($args !== null) {
                $this->args = $args;
                extract($this->args);
            }

            $page = VIEWS . $page . '.php';
            $template = $this->getTemplate($page);

            echo $template;
        }

        private function getTemplate($file) {
            ob_start();
            include($file);
            $template = ob_get_contents();
            ob_end_clean();
            return $template;
        }
    }
    ?>

Controller:

<?php
    class Page extends Controller {

        public function person($age) {
            $data['age'] = $age;
            $this->view('person', $data);
        }

    }
?>

View Contents:

</h1>My name is Dennis. My age is: <?php echo $age; ?></h1>

The end result is an undefined variable ($age).

  • 写回答

4条回答 默认 最新

  • douqian6194 2013-02-01 15:13
    关注

    The variables which you extract in view() are not available in getTemplate(). It is a different scope. You should instead extract them in the same method that does the rendering.

    Also, what you have there is not an MVC view. It's just a template. A view in MVC is an instance which is responsible for UI logic. It should be requesting the information, that it needs, from model layer and then, if a response is not simply a HTTP location header, creating the HTML using multiple templates.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配