2012-07-21 25 views
0

我有兩個文件:PHP我怎麼能返回通話功能(避免功能範圍)

的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函數的作用域內,所以不能工作,我怎樣才能將這個調用返回到loadTe中的require函數mplate? 我想使用$ this-> loadTemplate()這樣的單個函數將require包含在view()作用域中。並沒有使用require_once($ this-> getTemplatePath())

有什麼想法嗎?

回答

2

你不能。一般來說,你要做的是通過向變量傳遞數組($this->loadTemplate(array('myVar' => 'hello world'))),然後在loadTemplate方法中調用extract($vars)來完成。

+0

OFC這是可能的。這個解決方案比單純依賴類作用域消耗更多的內存和CPU時間。 – 2012-07-21 15:47:55

+0

這會讓'loadTemplate()'被聲明爲公共的,這會讓它變得毫無意義。此外,我所說的只是提問者無法實現他在問題中提出的問題,即需要使用一種方法的文件,而使用另一種方法的局部範圍。 – lanzz 2012-07-21 15:59:12

2

只需使用類成員來訪問的變量在viewscript

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 ?>