[英]PHP how can i return call function (to avoid function scope)
I have two files: 我有两个文件:
template.php: 的template.php:
<div><?php echo $myVar; ?></div>
controller 调节器
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");
}
}
but this must not works because the require is in scope of loadTemplate function, how can i return the call to require function in the loadTemplate? 但这不能正常工作,因为require处于loadTemplate函数的范围内,如何在loadTemplate中返回对require函数的调用? i want the require be included in the view() scope using single function like $this->loadTemplate(); 我希望使用$ this-> loadTemplate()之类的单个函数将需求包含在view()范围中; and not using require_once($this->getTemplatePath()) 而不使用require_once($ this-> getTemplatePath())
any idea? 任何想法?
You can't. 你不能 Generally what you're trying to do is accomplished by passing an array with your variables ( $this->loadTemplate(array('myVar' => 'hello world'))
) and then calling extract($vars)
in the loadTemplate
method. 通常,您要尝试通过传递带有变量的数组( $this->loadTemplate(array('myVar' => 'hello world'))
),然后在loadTemplate
方法中调用extract($vars)
来实现。
simply use class members to access the variables in your viewscript 只需使用类成员来访问视图脚本中的变量
Classes 类
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");
}
}
Template main.php 模板 main.php
Output: <?= $this->myVar ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.