如何在可跨模板使用的PHP中声明全局变量? [英] How do I declare a global variable in PHP I can use across templates?

查看:148
本文介绍了如何在可跨模板使用的PHP中声明全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在wordpress中,它调用header.php,然后调用任何模板名称或请求的页面.如何在php标头中声明一个变量,然后可以在其他模板中引用该变量?

In wordpress, it calls header.php then whatever template name or the page requested. How can I declare a variable in my php header which I can then refer to in my other templates?

推荐答案

答案很大程度上取决于您所需要的.如果正在开发主题,并且想要在所有文件中保持值不变,则可以将其放置在始终加载的主题目录的functions.php中.在那里定义的变量应该在主题的任何地方都可用.如果您分发主题,此方法将起作用.

The answer pretty much depends what you need it for. If you are developing a theme and want to keep values constant through all files you can place them in functions.php in the theme directory, which is always loaded. Variables defined there should be available everywhere in the theme. This works if you distribute the theme.

如果要根据自己的安装修改现有主题,可以按照建议将它们放在wp-config.php中,或者(一种更简洁的方法)可以

If you want to modify an existing theme for your needs on your own installation, you can either put them in wp-config.php, as suggested, or (a cleaner method) you can create a child theme of the theme you want to change. This will keep it separate from the wordpress core and will prevent theme updates from overwriting your changes.

我只是使用functions.php进行了尝试:

I just tried it using functions.php:

functions.php:

functions.php:

$variable = "value";

header.php:

header.php:

global $variable;
echo $variable;

为我工作.

这篇关于如何在可跨模板使用的PHP中声明全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆