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 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。