从包含的文件中获取变量

时间:2014-06-11 05:54:25

标签: php variables include require-once

如何使用包含文件中的变量,并将其用于其他包含的文件?

索引

<?php
$tmp = new template($connect);
$tmp->globals('index');
$logged_in = false; //works in all included files
?>
<html>
  <head>
    <?php $tmp->template('head'); ?> //class method to include file
  </head>
  <body>
    <?php echo $description; ?> //does not work either

include_head.php

 <title><?php echo $title; ?></title>//does not echo anything

index_globals.php

<?php
    $title="title";
    $description="description";   
 ?>

我如何包括

public function template($file){
    if(isset($file) && file_exists($this->dir.$file.".php")){
        ob_start();
        include($this->dir.$file.".php");
        $template = ob_get_contents();
        return $template;
     }
}

全局功能

public function globals($name){
  if(isset($name) && file_exists($this->dir.$name."_globals.php")){
      include($this->dir.$name."_globals.php");
  }
}

3 个答案:

答案 0 :(得分:1)

您可以通过返回数组而不是声明变量来“导入”全局变量:

<?php
// index_globals.php

return [
    'title' => 'title',
    'description' => 'description',
];

然后,从globals()函数将其导入本地属性:

private $context = [];

public function globals($name)
{
    if (isset($name) && file_exists($this->dir.$name."_globals.php")) {
        $this->context = include($this->dir.$name."_globals.php");
    }
}

最后,更新template()方法:

public function template($file)
{
    if (isset($file) && file_exists($this->dir.$file.".php")) {
        extract($this->context);
        ob_start();
        include($this->dir.$file.".php");
        $template = ob_get_contents();
        return $template;
     }
}

请注意,在这种情况下,您的索引也无法访问$description,但通过template实例获取访问权限应该不难。

答案 1 :(得分:1)

您需要将变量注入存储属性。

$tmp->set(array(
    'title' => 'hello world',
    'description' => 'this is the value'
));

// Or set a single value
$tmp->set('myCoolVariable', 'this is another value');

实现:

class template {
     protected $vars = array();

     public function set($key, $value)
     {
         if (is_array($key)) {
             // merge into existing
             $this->vars = array_merge($this->vars, $key);
         } else {
             // set a new variable with the name $key and value as $value
             $this->vars[$key] = $value;
         }
     }
}

然后在输出缓冲区方法中,extract()存储的变量

public function template($file)
{
    if (isset($file) && file_exists($this->dir.$file.".php")) {
        ob_start();
        extract($this->vars); // extract it so it is available for the current buffer
        include($this->dir.$file.".php");
        $template = ob_get_contents();
        ob_end_clean(); // don't forget to clean and turn it off
        return $template;
     }
}

答案 2 :(得分:0)

当您使用include()require()或者将该文件带入另一个文件的PHP中包含文件时,包含的文件基本上嵌入到包含它的文件中。这就像将所包含文件中的所有代码写入调用include(*file*)的文件中一样。

简单地说:当你包含一个文件时,如果你成功地用include()require()或类似提到的方法包含它,那么所有变量都可以像声明的任何其他变量一样使用