dongzhuo3059 2016-08-14 16:16
浏览 8
已采纳

PHP如何在MVC模式中从布局渲染函数?

I've a code with im working for.

  class View
{
    public $model;
    public $function;
    public $content;

    public function __construct( $model )
    {
        $this->model = $model;
        $this->templateLoader( get_class( $this->model ));
    }

    public function templateLoader( $model )
    {
        $template       = "View/Layout/" . $model . ".tpl";

        if ( file_exists( $template ))
        {
            $this->getContent( $template );
            $this->searchForTags();
            $this->runFunction();
        }
    }

    public function getContent( $template )
    {
        $this->content = file_get_contents( $template );
    }

    public function searchForTags()
    {
        $start = strpos( $this->content, '<%')+strlen('<%');
        $end = strpos( $this->content, '%>');
        $part = $end - $start;

        if ( $part > 0)
            $this->function = substr($this->content, $start, $part);
    }

    public function runFunction()
    {
        if ( $this->function )
        {
            var_dump( $this->model->{$this->function} );
        }
    }
}

This class load my template regarding classname. In the template if i have function example:

<td class="right error"> <% getLoginValidatorMsg() %></td>

i want to run it and replace into the value before it shows in my template. Somehow i cant run above function. Error:

Notice: Undefined property: LoginForm::$ getLoginValidatorMsg() in /media/htdocs/ver1/loginmanager/init/View.php on line 54

If i try to run:

$this->model->getLoginValidatorMsg();

will return me the value what i looking for.

  • 写回答

3条回答 默认 最新

  • duanao6704 2016-08-14 16:50
    关注

    It appears from the error you have a space between $ and getLoginValidatorMsg so you need to remove that space using a correctly placed trim() or just str_replace() on the whole thing. Also, it is saying it's looking for a property so you need to add () on your $this->model->{$this->function} so it turns it to a method:

    $this->model->{$this->function}();
    

    Alternatively, you can use call_user_func() / call_user_func_array().

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

报告相同问题?

悬赏问题

  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现
  • ¥15 vscode的红色箭头爆红和has no default export报错
  • ¥15 关于#sql#的问题:#情况描述 在用vs对项目进行调试时,出现找不到网络路径,然后查看SQL配置工具,发现SQL服务显示远程调用过程失败(相关搜索:防火墙)
  • ¥15 eNSP中基于默认路由及浮动路由的公司与分部互联和校园网综合项目
  • ¥15 主要进行描述泥浆在管路不同区段泥浆的密度不相同,泥浆的密度有高有低,此时管路的摩阻分布需要怎么计算,(标签-matlab)
  • ¥40 通过编制程序计算圆管内层流充分发展对流换热,参数如图5-4,以及公式5-16所示,要求用表5-6对程序计算准确性进行验证
  • ¥20 该学习哪个编程语言? AI会取代程序员吗?
  • ¥15 ensp如何拼通IP地址
  • ¥15 saber软件导入Ibis模型报错