在header.php中设置变量但在footer.php中没有看到

Nau*_*der 16 wordpress

在wordpress中,我在header.php中设置了一个变量

<?php
$var= 'anything'
?>
Run Code Online (Sandbox Code Playgroud)

但是当我回应它时,在footer.php中

<?php
echo $var;
?>
Run Code Online (Sandbox Code Playgroud)

我没有打印出来......为什么!>

Mac*_*ade 25

您不在同一范围内,因为页眉和页脚文件包含在函数体中.所以你要声明一个局部变量,并引用另一个局部变量(来自另一个函数).

所以只需将您的变量声明为全局变量:

$GLOBALS[ 'var' ] = '...';
Run Code Online (Sandbox Code Playgroud)

然后:

echo $GLOBALS[ 'var' ];
Run Code Online (Sandbox Code Playgroud)


use*_*011 11

我知道你已经接受了这个问题的答案; 但是,我认为对变量范围问题有一个更好的方法,而不是将变量传递到$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()
    {
    }


}
Run Code Online (Sandbox Code Playgroud)

在你的主题保存这个类的地方,例如,/classes/registry.class.php包括在你的上面的文件functions.php文件:包括;(get_template_directory()"/classes/registry.class.php".)

示例用法

存储变量:

$registry = new Registry();
$registry->my_variable_name = "hello world";
Run Code Online (Sandbox Code Playgroud)

检索变量:

echo '<h1>' .  $registry->my_variable_name . '</h1>'
Run Code Online (Sandbox Code Playgroud)

注册表将接受任何变量类型.

注意:我通常使用SplObjectStorage作为内部数据存储区,但是我已经将它换成了常规的ole数组.