繁体   English   中英

从包含的文件中获取变量

[英]Get variables from included file

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

指数

<?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");
  }
}

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

<?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实例获得访问权限并不难。

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

$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;
     }
}

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

简而言之:如果您成功包含了include()require()或类似提到的方法,那么在包含文件时,所有变量都可以像声明的任何其他变量一样使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM