[英]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.