我正在尝试在php中创建view($path,$data)函数,主要功能是从目录中包含特定文件,并将数据/变量传递到该页面中,我设法创建了$path并能够包含定义路径,现在我的下一步是将$data值传递到我包含的页面中,并希望将每个数组标签转换为变量.
我的php类在classes.php下面.
define("SITE_NAME", "process");
class helpers {
public function view($path, $data)
{
$dir = $_SERVER['DOCUMENT_ROOT'].SITE_NAME."/";
include($dir.$path.".php");
return extract($data);
}
}
在我的index.php
require_once('classes.php');
$helper = new Helpers();
$data['title'] = "My Test";
$data['test'] = "test1";
$helper->view('test',$data);
所以现在在我的test.php上,我试图回显$title,我假设它将返回My Test的值,以测试我是否从index.php获取值,我能够使用print_r输出$data
数组([title] =>我的Test [test] => test1)
任何建议,我如何实现?我正在尝试extract()函数,但不知道我的语法是否正确.谢谢!
解决方法:
因为收益仅限于一个值.
通过提取它,您将获得一个值并将其拆分为多个值.
就我个人而言,我避免在代码中使用诸如extract和$$var之类的东西,因为它会破坏我的IDE,并使可读性几乎变得不可能.就是说,在这种情况下使用它确实很有意义,因为它在有限的范围内,从而限制了无意中意外覆盖另一个变量的可能性.
A function can not return multiple values, but similar results can be obtained by returning an array.
和
extract — Import variables into the current symbol table from an array
符号表〜范围
进一步
Return Values: Returns the number of variables successfully imported
into the symbol table
public function view($path, $data)
{
$dir = $_SERVER['DOCUMENT_ROOT'].SITE_NAME."/";
include($dir.$path.".php");
return extract($data); //returns the variables successfully imported from $data
}
.
如您所见,调用return后,将结束当前函数的执行并关闭该作用域.您将不得不重新安排这些,因此变量分配首先发生.
我假设方法中包含的文件是这样的,它不在OP中.
= $title; ?>
从技术上讲,您无需返回任何内容,因为HTML自然会被输出缓冲区捕获并在脚本完成执行时显示.但是,这不是很干净.正确的方法是控制输出缓冲区,如下所示:
public function view($path, $data)
{
$dir = $_SERVER['DOCUMENT_ROOT'].SITE_NAME."/";
extract($data); //variables must exist before importing where they are used.
ob_start();
include($dir.$path.".php"); //capture this output
$view = ob_get_clean();
return $view;
}
$out = $helper->view('test',$data); //out now contains the HTML output from the included file.
然后,您可以将其回显. IMO这是更好的方法,因为您可以将HTML输出插入另一个数据数组并将其通过管道传递到另一个模板.这对于可重复使用的页眉,页脚或导航栏等很有用.
考虑一下
$head['page_title'] = "My Test";
$body['head'] = $helper->view('header',$head); //create head and assign to body
$body['name'] = 'John Smith';
echo $helper->view('body',$body); //create body (with head inserted) and echo
和header.php
= $page_title; ?>和body.php
= $head; ?>
= $name; ?>
现在的输出将是这样的
My TestJohn Smith
现在,两个页面都合并为一个页面,即输出.您可以将其设置为所需的可重用性级别,但这将为您节省大量的键入时间,并使维护视图的方式更加容易.
但是,正如我所说,您可以简单地让它自然输出
public function view($path, $data)
{
$dir = $_SERVER['DOCUMENT_ROOT'].SITE_NAME."/";
extract($data); //variables must exist before importing where they are used.
include($dir.$path.".php"); //capture this output
}
//outputs when script is done.
标签:php,function
来源: https://codeday.me/bug/20191025/1931405.html