PHP 使用 extract() 将数组值作为变量传递并将其显示在页面上

标签 php function

我正在尝试在 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] => test1 )

有什么建议可以实现吗?我正在尝试使用 extract() 函数,但不知道我的语法是否正确。提前致谢!

最佳答案

因为return仅限于一个值。

通过提取它,您将获取一个值 array 并将其拆分为多个值。

就我个人而言,我避免在我的代码中使用 extract$$var 之类的东西,因为它会破坏我的 IDE 并使可读性几乎不可能。也就是说,在这种情况下使用它确实有意义,因为它在一个有限的范围内,这限制了无意中意外覆盖另一个变量的可能性。

http://php.net/manual/en/functions.returning-values.php

A function can not return multiple values, but similar results can be obtained by returning an array.

http://php.net/manual/en/function.extract.php

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 中。

    <h1><?= $title; ?></h1>

从技术上讲,您不需要返回任何内容,因为 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

<title><?= $page_title; ?></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

和 body.php

<!DOCTYPE html>
<html>
    <head>
        <?= $head; ?>
    </head> 
    <body>
       <p><?= $name; ?></p>
    </body> 
 </html>

现在的输出应该是这样的

<!DOCTYPE html>
<html>
   <head>
      <title>My Test</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  </head>   
  <body>
     <p>John Smith</p>
  </body>   
</html>

现在两个页面合二为一,即输出。您可以将它带到您想要的任何级别的可重用性,但它会为您节省大量的输入,并使维护 View 更容易。

但是,正如我所说,您可以简单地让它自然输出

    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 使用 extract() 将数组值作为变量传递并将其显示在页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474487/

相关文章:

php - 访问 "CSS"中的全局变量(style.php)

r - 我想对许多数据框进行关联

javascript - 如何创建一个函数,通过 onmouseover 将我的段落更改为 img

MySQL 函数不返回正确的结果

php - sql 计算来自特定字段的唯一值

php - Laravel 获取前 5 个 foreach

javascript - 日期时间选择器 - Chrome 和 Firefox 之间的奇怪行为

php - 尝试打印数组中的值时出现非法字符串偏移

python - kivy python通过单击按钮将参数传递给函数

c - 为什么数组参数的大小与 main 中的大小不同?