我知道您已经接受了这个问题的答案;但是,我认为对于变量范围问题,有一种比将 vars 传递到 $GLOBALS 数组更好的方法。
以您主题中的functions.php 文件为例。此文件包含在get_header() 和get_footer() 函数的范围之外。事实上,它取代了你在主题中可能做的任何其他事情(我也相信插件范围——尽管我必须检查一下。)
如果你想设置一个你想在你的页眉/页脚文件中使用的变量,你应该在你的 functions.php 文件中进行设置,而不是污染 $GLOBALS 数组。如果您有更多想要确定的变量,请考虑使用带有 getter/setter 的基本 Registry 对象。这样,您的变量将更好地封装在您可以控制的范围内。
注册表
这是一个示例 Registry 类,可以帮助您在以下情况下入门:
<?php
/**
* Registry
*
* @author Made By Me
* @version v0.0.1
*/
class Registry
{
# +------------------------------------------------------------------------+
# MEMBERS
# +------------------------------------------------------------------------+
private $properties = array();
# +------------------------------------------------------------------------+
# ACCESSORS
# +------------------------------------------------------------------------+
/**
* @set mixed Objects
* @param string $index A unique index
* @param mixed $value Objects to be stored in the registry
* @return void
*/
public function __set($index, $value)
{
$this->properties[ $index ] = $value;
}
/**
* @get mixed Objects stored in the registry
* @param string $index A unique ID for the object
* @return object Returns a object used by the core application.
*/
public function __get($index)
{
return $this->properties[ $index ];
}
# +------------------------------------------------------------------------+
# CONSTRUCTOR
# +------------------------------------------------------------------------+
public function __construct()
{
}
}
将此课程保存在您的主题中的某个地方,例如/classes/registry.class.php 在functions.php 文件的顶部包含该文件:include(get_template_directory() .'/classes/registry.class.php');
示例用法
存储变量:
$registry = new Registry();
$registry->my_variable_name = "hello world";
检索变量:
echo '<h1>' . $registry->my_variable_name . '</h1>'
注册表将接受任何变量类型。
注意:我通常使用 SplObjectStorage 作为内部数据存储,但在这种情况下,我已将其换成常规的 ole 数组。