簡體   English   中英

PHP如何返回調用函數(以避免函數作用域)

[英]PHP how can i return call function (to avoid function scope)

我有兩個文件:

的template.php:

<div><?php echo $myVar; ?></div>

調節器

class MyClass extends Base {
    public function view() {
        $myVar = 'hello world';
        $this->loadTemplate('main');
    }
}
abstract class Base {
    public function loadTemplate($template) {
        require_once("templates/$template.php");
    }
}

但這不能正常工作,因為require處於loadTemplate函數的范圍內,如何在loadTemplate中返回對require函數的調用? 我希望使用$ this-> loadTemplate()之類的單個函數將需求包含在view()范圍中; 而不使用require_once($ this-> getTemplatePath())

任何想法?

你不能 通常,您要嘗試通過傳遞帶有變量的數組( $this->loadTemplate(array('myVar' => 'hello world')) ),然后在loadTemplate方法中調用extract($vars)來實現。

只需使用類成員來訪問視圖腳本中的變量

class MyClass extends Base
{
    public function view()
    {
        $this->myVar = 'hello world';
        $this->loadTemplate('main');
    }
}

abstract class Base
{
    public function loadTemplate($template)
    {
        require_once("templates/$template.php");
    }
}

模板 main.php

Output: <?= $this->myVar ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM