如何设置和使用全局变量?还是为什么根本不使用它们
-
-
该语句回显了哪个链接esc_url($ category_link_prop);显示?您期望的链接是什么?Which link does this statement echo esc_url( $category_link_prop ); displays ? What is your expected link?
- 1
- 2013-03-04
- Vinod Dalvi
-
为什么您不打算在计划使用全局变量的地方仅使用"get_cat_ID(****)".我怀疑您这样做的方式是否会带来速度优势.从可读性的角度来看,"get_cat_ID(****)"很容易获得帮助.Why would you not just use 'get_cat_ID( **** )' where ever you planned to use the global variable. I doubt there would be any speed advantage the way your doing it. From a readability standpoint, 'get_cat_ID( **** )' wins hands down.
- 1
- 2013-03-04
- Chris Strutton
-
你能改写吗?我阅读了您的问题,但仍然不确定您想做什么以及为什么要这样做.我的一般建议是不要使用全局变量,也不要污染全局范围Can you reword? I read your question and I'm still unsure of what you want to do and why you want to do it. My general advice would be to not use global variables, and not to pollute the global scope
- 1
- 2013-03-04
- Tom J Nowell
-
@VinodDalvi我希望获得"the提案"类别的链接.@VinodDalvi I was hoping to get the link to the category with the slug proposal'.
- 0
- 2013-03-05
- JPollock
-
@TomJNowell我将在一分钟内进行编辑以反映我正在使用它进行导航,因此无论如何它们几乎都可以在任何页面上使用.@TomJNowell I will edit in a minute to reflect that I'm using this for navigations, such they will be used on pretty much any page anyway.
- 0
- 2013-03-05
- JPollock
-
@ChrisStruttonget_cat_id()并没有给我五个我所需要的东西(即链接,标题等).可读性对我来说不是一个大问题,我将是唯一阅读此书的人.@ChrisStrutton get_cat_id() doesn't five me everything I need (ie the link, the title, etc.). Readability isn't a huge concern for me, I will be the only oen reading this.
- 0
- 2013-03-05
- JPollock
-
这听起来有点像[X/Y问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).也许您应该备份并确切说明您想要的结果是什么.我敢肯定,比设置一堆全局变量然后在其他地方的导航中硬编码对它们的引用,还有一种更为优雅的解决方案this is sounding a bit like an [X/Y Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). perhaps you should back up and explain exactly what your desired outcome is. I'm certain there's a far more elegant solution than setting a bunch of global vars to then just hardcode references to them in a nav elsewhere
- 1
- 2013-03-05
- Milo
-
@Milo非常好.我的实际问题是,到目前为止,我的主题有4种不同的导航方式:1是标准的顶部栏,而3仅根据特定条件显示.它们都显示出大致相同内容的不同组合,并且顺序任意,并且会随着项目的进行而改变.我的问题是,如果我对它们进行硬编码,我将不得不一遍又一遍地对相同的事物进行硬编码,然后每次更改时都对同一事物进行4次更改.@Milo Excellent point. My actual problem is my theme has 4 different navigations (so far.) 1 that is a standard top bar, and 3 that only display based on certain conditions. They all show different combinations of roughly the same things and are in arbitrary orders and are going to change as the project goes on. My problem is if I hard-code them, I will have to hardcode the same thing over and over again, and then change the same thing 4 times every time something changes.
- 0
- 2013-03-05
- JPollock
-
创建一个函数,该函数根据传递给它的上下文输出菜单,这样您就可以将所有菜单逻辑和关联的var封装在一个地方.create a function that outputs your menu based on the context you pass to it, that way you can keep all of the menu logic and associated vars encapsulated in one place.
- 2
- 2013-03-05
- Milo
-
@Milo我就是从这里开始的,但是我知道我有一个用于顶部栏导航的功能;边栏导航的一项功能根据条件的不同而增加到4个不同的版本;以及页面模板中子导航的一个功能,随着这种情况的继续,将会有更多的功能.我无法提出一种将所有这些组合成一个函数的理智方法.@Milo That's what I started with, but know I have one function for top bar navigation; one function for a side bar nav which just grew to 4 different versions based on conditionals; and one function for a sub-nav in a page template and there are going to be more of those as this goes on. I can't come up with a sane way of combining all of those into one function.
- 0
- 2013-03-05
- JPollock
-
@Milo我也希望能够将它们用作网站文本中网站各个部分的链接,无论是帖子(如果可行)还是页面模板.@Milo Also I want to be able to use these as links to various parts of the site in the text of the site, either in posts (if that works) or in page templates.
- 0
- 2013-03-05
- JPollock
-
4 个回答
- 投票数
-
- 2013-03-04
尽管我强烈建议您这样做,但它不会加快速度,但您的用法不正确.
WordPress已经将这些内容缓存在对象缓存中,您不需要存储结果并重复使用,WP已经做到了.
由于这种微优化,您的代码很有可能运行得较慢,而不是更快!
如何使用全局变量
当您尝试使用全局变量时,必须首先指定
global
关键字.您在定义其值时已在此处指定了它,但是在该范围之外,需要将其重新声明为全局范围变量.例如在
functions.php
中:function test() { global $hello; $hello = 'hello world'; } add_action( 'after_setup_theme', 'test' );
在
single.php
中,这将不起作用:echo $hello;
因为未定义
$hello
.但是,将起作用:global $hello; echo $hello;
当然,您都不应该这样做. WordPress已经尝试将这些内容缓存在对象缓存中.
全局变量的缺点和危险
执行此操作不会使速度增加(您可能会看到速度的微小降低),您得到的只是额外的复杂性,并且需要键入很多不必要的全局声明.
您还将遇到其他问题:
- 无法为其编写测试的代码
- 每次运行时行为不同的代码
- 与共享名称空间中的变量名称冲突 忘记声明
- 意外错误
- 代码数据存储完全缺乏结构
- 还有更多
global
的您应该改用什么?
使用结构化数据(例如对象或依赖项注入,或者在您的情况下使用一组函数)会更好.
静态变量
静态变量不好,但是可以将它们视为全局变量的邪恶表亲.静态变量是全局变量,泥泞的面包是氰化物.
例如,这是一种通过静态变量执行类似操作的方法,例如
function awful_function( $new_hello='' ) { static $hello; if ( !empty( $new_hello ) ) { $hello = $new_hello; } return $hello; } awful_function( 'telephone' ); echo awful_function(); // prints telephone awful_function( 'banana'); echo awful_function(); // prints banana
单子
字母类似于静态变量,不同的是该类包含带有该类实例的静态变量.它们和全局变量一样糟糕,只是语法不同.避免它们.
WP_Cache,您尝试做的事,但WP已经做到了
如果您真的想通过将数据存储在某个地方来节省时间以供重用,请考虑将
WP_Cache
系统与wp_cache_get
等一起使用$value = wp_cache_get( 'hello' ); if ( false === $value ) { // not found, set the default value wp_cache_set( 'hello', 'world' ); }
现在WordPress将在请求的整个生命周期中缓存该值,并在调试工具中显示该值,如果您有对象缓存,它将在请求中持久存在
旁注1:我要指出的是,有些人试图将数据持久保存在请求中的全局变量中,而没有意识到这不是PHP的工作方式.与Node应用程序不同,每个请求都加载该应用程序的新副本,然后在请求完成时死亡.因此,在一个请求上设置的全局变量无法保存到下一个请求
旁注2:从更新后的问题来看,您的全局变量根本不会提高性能.您只需要在需要时生成HTML,它就会以同样快的速度运行,甚至可能快一点.这是微观优化.
While I strongly advise against this, and it will not speed things up, your usage is incorrect.
WordPress already caches these things in the object cache, you don't need to store the result and reuse, WP does that already.
It's very likely your code is running slower as a result of this micro-optimisation, not faster!
How To Use Globals
When you try to use a global you must specify the
global
keyword first. You have specified it here when defining its value, but outside of that scope it needs to be redeclared as a global scope variable.e.g. in
functions.php
:function test() { global $hello; $hello = 'hello world'; } add_action( 'after_setup_theme', 'test' );
In
single.php
, this will not work:echo $hello;
Because
$hello
is undefined. This however will work:global $hello; echo $hello;
Of course you should do neither. WordPress already attempts to cache these things in the object cache.
Disadvantages and Dangers of Global Variables
You will see no speed increase from doing this ( you may see a tiny speed decrease ), all you will get is additional complexity and the need to type out a lot of global declarations that aren't necessary.
You'll also encounter other issues:
- code that's impossible to write tests for
- code that behaves differently every time it runs
- clashes in variable names from a shared name space
- accidental bugs from forgetting to declare
global
- a complete lack of structure to your codes data storage
- and many more
What Should You Use Instead?
You would be better off using structured data, such as objects or dependency injection, or in your case, a set of function.
Static Variables
Static variables aren't good, but think of them as the slightly less evil cousin of global variables. Static variables are to global variables, what mud covered bread is to cyanide.
For example, here is a means of doing something similar via static variables e.g.
function awful_function( $new_hello='' ) { static $hello; if ( !empty( $new_hello ) ) { $hello = $new_hello; } return $hello; } awful_function( 'telephone' ); echo awful_function(); // prints telephone awful_function( 'banana'); echo awful_function(); // prints banana
Singletons
Singletons are like static variables, except the class contains a static variable with an instance of that class. They're just as bad as global variables, just with different syntax. Avoid them.
WP_Cache, The Thing You Tried to Do But WP Already Does It
If you really want to save time by storing data somewhere to re-use, consider using the
WP_Cache
system withwp_cache_get
etc e.g.$value = wp_cache_get( 'hello' ); if ( false === $value ) { // not found, set the default value wp_cache_set( 'hello', 'world' ); }
Now the value will get cached for the life of the request by WordPress, show up in debugging tools, and if you have an object cache it'll persist across requests
Sidenote 1: I would note, that some people try to persist data in global variables across requests, unaware that this is not how PHP works. Unlike a Node application, each request loads a fresh copy of the application, which then dies when the request is completed. For this reason global variables set on one request do not survive to the next request
Sidenote 2: Judging from the updated question, your global variables give you no performance gain at all. You should just generate the HTML as and when you need it and it would run just as fast, perhaps even a tiny bit faster. This is micro-optimisation.
-
我知道使用全局范围有点麻烦,但是大多数(如果不是全部的话)这些变量将在每个页面上使用.我愿意接受更好的主意.我将编辑问题以使我的意图更加清楚.顺便说一句,当我做``根据您的建议.谢谢!I know it's a little nuts to use the global scope, but most, if not all of these variables will be used on every page. I'm open to better ideas. I am going to edit the question to make my intent a little clearer. BTW it works perfectly fine when I do `` as per your suggestion. Thanks!
- 0
- 2013-03-05
- JPollock
-
嗯,如果我的解决方案有效,您能否标记为已接受?您的全局变量与进行原始调用一样快,您可能想尝试使用函数,这样就无需键入两行,更好的是,单例的,更好的是,使所有这些动态化,通过get_template_part包含的模板部分Ah if my solution works, could you mark as accepted? Your global variables are just as fast as making the original call, you may want to try instead using functions so you don't need to type out 2 lines, better yet, a singleton, better yet, make all of that dynamic and in a template part included via get_template_part
- 2
- 2013-03-05
- Tom J Nowell
-
尽管我可能会采用@MarkKaplun提出的以下策略之一,但现在被标记为我现在正在做的事情.使用get_template_part()是一个有趣的主意,但是我不确定我是否希望像这样的短文件充满目录...Marked as accepted as its what I am doing now though I may go with one of the strategies @MarkKaplun is suggesting below. Using get_template_part() is an interesting idea, but I'm not sure I want to have a dir full of short files like that...
- 0
- 2013-03-06
- JPollock
-
哦,不,您不希望每个类别都有一个文件,您只需要一个获取当前类别名称并使用该名称的文件即可.您不必对任何内容进行硬编码,想象一下对所有内容进行硬编码的麻烦oooh no no you wouldn't want a file for each category, you'd want just the one that grabs the current category name and uses that. You shouldn't have to hardcode anything, imagine the hassle of hardcoding it all
- 0
- 2013-03-06
- Tom J Nowell
-
我将代码放入了活跃的child-functions.php中.但是我无法从"正常"数据库生成的帖子中调用的php-include文件中访问变量.请告诉我,我该怎么办?(当然,我将其定义为全局).I put the code in my child-functions.php which is active. But I can not access the variable in a php-include file I call from a "normal" database-generated post. Please advise me, what do I do wrong? (I define it as global, of course.)
- 0
- 2018-06-03
- ycc_swe
-
每次使用时都必须声明"global".一旦在任何地方都可以使用,它就不是一种用途,您必须每次都使用它,任何形式的例外都没有.但是正如我在问题中所说的那样,全局变量是不好的做法,有问题,而不是您要寻找的解决方案.即使是单身的邪恶也将是一个更好的解决方案You have to declare `global` every time you use it. It isn't a use once works everywhere affair, you have to use it each, and every, single time, no exceptions of any kind. But as I say in my question, global variables are bad practice, problematic, and not the solution you're looking for to your problem. Even the evil that is singletons would be a better solution
- 0
- 2018-06-03
- Tom J Nowell
-
谢谢,谢谢您的评论.我声明并使用了它,但是在某个地方我肯定犯了一个错误.只是对我没用.我尝试了不同的方法.终于,[这个](https://gist.github.com/aahan/7444046)工作了.我同意您在Globals上所说的话,但有时个人网站需要快速修复.谢谢.Thank you, I appreciate your comment. I declared it and used it but somewhere I must have made a mistake. It just didn't work for me. I tried different approaches. Finally [this one](https://gist.github.com/aahan/7444046) worked. I agree with what you say on globals, but sometimes a quick fix is needed for a personal site. Thanks.
- 0
- 2018-06-03
- ycc_swe
-
- 2013-03-04
不要使用全局变量,就这么简单.
为什么不使用全局变量
因为使用全局变量使长期维护该软件更加困难.
- 可以在代码中的任何位置声明声明全局变量,或者根本不声明全局变量,因此没有地方可以本能地查找关于全局变量用途的注释
- 在阅读代码时,您通常会认为变量是函数的局部变量,并且不了解更改函数中的值可能会导致系统范围的变化.
- 如果它们不处理输入,则在使用相同参数调用函数时,它们应该返回相同的值/输出.在函数中使用全局变量会引入其他参数,这些参数不在函数声明中记录.
- 全局变量没有任何特定的初始化构造,因此,您永远无法确定何时可以访问全局变量的值,并且在初始化之前尝试访问全局变量也不会出错.
- 其他人(也许是一个插件)可能使用具有相同名称的全局变量,破坏了代码,或者根据初始化顺序破坏了代码.
WordPress核心有很多使用全局变量的方法.在尝试理解诸如
the_content
之类的基本功能如何工作时,您突然意识到$more
变量不是局部变量而是全局变量,需要搜索整个核心文件以了解何时设置为true.那么,当尝试停止复制和粘贴多行代码而不是将第一次运行的结果存储在全局变量中时,该怎么办?功能和OOP有几种方法.
甜味剂功能.它只是用于保存复制/粘贴的包装/宏
// input: $id - the category id // returns: the foo2 value of the category function notaglobal($id) { $a = foo1($id); $b = foo2($a); return $b; }
好处是,现在有了以前的全局函数的文档,并且当返回的值不是您期望的值时,您很明显需要进行调试.
一旦添加了甜味剂,就可以在需要时很容易地缓存结果(仅当发现该函数需要很长时间才能执行时才这样做)
function notaglobal($id) { static $cache; if (!isset($cache)) { $a = foo1($id); $b = foo2($a); $cache = $b; } return $cache; }
这为您提供了与全局相同的行为,但具有每次访问时都确保初始化的优点.
您可以在OOP中使用类似的模式.我发现OOP通常不会在插件和主题中添加任何价值,但这是一个不同的讨论
class notaglobal { var latestfoo2; __constructor($id) { $a = foo1($id); $this->latestfoo2 = foo2($a) } } $v = new notaglobal($cat_id); echo $v->latestfoo2;
这是一个笨拙的代码,但是如果由于要一直使用它们而要预先计算几个值,那么这可以作为一种方法.基本上,这是一个以有组织的方式包含所有全局变量的对象.为避免将此对象的实例设置为全局对象(您只希望一个实例,否则将重新计算值),则可能需要使用单人模式(有人认为这是个坏主意,YMMV)
我不喜欢直接访问对象属性,因此在我的代码中它将扭曲更多
class notaglobal { var latestfoo2; __constructor() {} foo2($id) { if (!isset($this->latestfoo2)) { $a = foo1($id); $b = foo2($a); $this->latestfoo2= $b; } return $this->latestfoo2; } } $v = new notaglobal(); echo $v->foo2($cat_id);
Don't use global variables, as simple as that.
Why not to use globals
Because the use of globals makes it harder to maintain the software in the long term.
- A global can be declared anywhere in the code, or nowhere at all, therefor there is no place in which you can instinctivly look at to find some comment about what the global is used for
- While reading code you usually assume that variables are local to the function and don't understand that changing their value in a function might have a system wide change.
- If they don't handle input, functions should return the same value/output when they are called with the same parameters. The use of globals in a function introduce additional parameters which are not document in the function declaration.
- globals don't have any specific initialization construct and therefor you can never be sure when you can access the value of the global, and you don't get any error when trying to access the global before initialization.
- Someone else (a plugin maybe) might use globals with the same name, ruining your code, or you ruining its depending on initialization order.
WordPress core has way way way much to much use of globals. While trying to understand how basic functions like
the_content
work, you suddenly realize that the$more
variable is not local but global and need to search whole of the core files to understand when is it set to true.So what can be done when trying to stop copy&pasting several lines of code instead of storing the first run result in a global? There are several approaches, functional and OOP.
The sweetener function. It is simply a wrapper/macro for saving the copy/paste
// input: $id - the category id // returns: the foo2 value of the category function notaglobal($id) { $a = foo1($id); $b = foo2($a); return $b; }
The benefits are that now there is a documentation to what the former global does, and you have an obvious point for debugging when the value being returned is not the one you expect.
Once you have a sweetener it is easy to cache the result if needed (do it only if you discover that this function takes a long time to execute)
function notaglobal($id) { static $cache; if (!isset($cache)) { $a = foo1($id); $b = foo2($a); $cache = $b; } return $cache; }
This gives you the same behavior of a global but with the advantage of having an assured initialization every time you access it.
You can have similar patterns with OOP. I find that OOP usually doesn't add any value in plugins and themes, but this is a different discussion
class notaglobal { var latestfoo2; __constructor($id) { $a = foo1($id); $this->latestfoo2 = foo2($a) } } $v = new notaglobal($cat_id); echo $v->latestfoo2;
This is a clumsier code, but if you have several values that you would like to precompute because they are always being used, this can be a way to go. Basically this is an object that contain all of your globals in an organized way. To avoid making an instance of this object a global (you want ont one instance otherwise you recompute the values) you might want to use a singleton pattern (some people argue it is a bad idea, YMMV)
I don't like to access an object attribute directly, so in my code it will warpe some more
class notaglobal { var latestfoo2; __constructor() {} foo2($id) { if (!isset($this->latestfoo2)) { $a = foo1($id); $b = foo2($a); $this->latestfoo2= $b; } return $this->latestfoo2; } } $v = new notaglobal(); echo $v->foo2($cat_id);
-
请**不要喊**.介意解释原因并提供某种引用?Please, **don't shout**. Mind to explain why and provide some kind of citation?
- 7
- 2013-03-04
- brasofilo
-
我认为您误解了答案.如果他不打算通过将值存储在全局变量中来进行早期优化,那么他的代码就会奏效.大声疾呼是因为遵循基本的既定软件开发原则是一件不够强调的事情.不了解这些基本原理的人(可在您当地的google上找到)不应将代码散布到网络上.I think that you misunderstood the answer. If he wasn't trying to do early optimization by storing values in global variables his code would have worked. The shouting is because following basic established software development principles is something that can't be emphasized enough. People who do not understand those basic principle (available at your local google) should not spread code over the net.
- 0
- 2013-03-04
- Mark Kaplun
-
嗨,马克,很抱歉,我的评论和您的回答一样短,我应该让自己更加清楚:1)IMO,大胆的观点足以说明这一点.2)尽管有时无话可说,但我怀疑只有一行回答:[发布单行答案是否可以,或者作为注释更好?](http://meta.stackexchange.com/q/129019/185667)Hi, Mark, apologies, my Comment was as short as your Answer and I've should made myself clearer: 1) IMO, bold is enough to make a point. 2) Although sometimes there's nothing more to say, I suspect of one line Answers: [Is it okay to post a one-line answer, or would those be better as comments?](http://meta.stackexchange.com/q/129019/185667)
- 0
- 2013-03-04
- brasofilo
-
是的,只有在发布之后,我才意识到我应该使用粗体.将解决这个问题yeh, only after I have posted I realized I should have used bold. will fix that asspect
- 0
- 2013-03-04
- Mark Kaplun
-
IMO这是一个答案,从Google来到这里的人们应该看到,甚至立即考虑使用globals是一个坏主意.IMO this is an answer, people who come here form google should see that it is a bad idea to even think about using globals right away.
- 1
- 2013-03-04
- Mark Kaplun
-
仅仅说"不做X"还不够,您必须说明原因,或者看起来像是一时兴起It's not enough to say dont do X, you have to explain why or you look like you're saying it on a whim
- 6
- 2013-03-04
- Tom J Nowell
-
@MarkKaplun您将怎么做,以避免不得不一遍又一遍地写相同的设置,然后如果其中任何一部分发生更改,则必须手动更改每个设置?@MarkKaplun What would you do instead to avoid having to write the same set thing over and over again, and then have to change each one manually if any part of it changes?
- 0
- 2013-03-05
- JPollock
-
@JPollock,编辑了答案.@JPollock, edited the answer.
- 0
- 2013-03-05
- Mark Kaplun
-
@TomJNowell,我感到很有趣,我是唯一一个对问题本身不满意的人,因为它显然超出了WASE的范围.我看不到扩展本不应该在这里开始的主题的价值.@TomJNowell, I find it funny that I was the only one downvoting the question itself, as it was obviously outside of the scope of WASE. I didn't see the value of expanding on a subject which should not have been started here at all.
- 1
- 2013-03-05
- Mark Kaplun
-
@MarkKaplun太棒了.您的第一个解决方案听起来是最好的.我将尝试缓存,这可能是必要的.我不确定为什么这不在此stackexchange的范围之内?问题是关于PHP的,但事实证明它与WordPress如何处理全局变量有关.案例也特定于WordPress导航菜单.@MarkKaplun Awesome. Your first solution sounds like the best. I will experiment with caching, which will probably be necessary. I'm not sure why this is outside the scope of this stackexchange? The question is about PHP, but it turns out it has everything to do with how WordPress deals with globals. Also the case is specific to WordPress navigation menus.
- 0
- 2013-03-06
- JPollock
-
" WordPress核心拥有大量使用全局变量的方式."我想说Wordpress根本没有* any *全局变量,但这只是我自己."WordPress core has way way way much to much use of globals." I'd say Wordpress having *any* globals at all is way too many, but that's just me.
- 0
- 2014-04-02
- R Porter
-
@MarkKaplun感谢您的实用方法.如果我们采用它,您是否可以进行更新以显示回退值为$ ID的情况,如果由于某种原因它不存在,未设置或不是正整数,该状态如何?@MarkKaplun thank you for your functional approach. In the event that we take it, could you make an update to show us how it should look like with a fallback value of $ID, if for some reason it didn't exist, was not set or was not a positive integer?
- 0
- 2016-10-21
- klewis
-
全局变量通常由于许多原因而不好,但是说从未使用全局变量的人也是如此.globals can often be bad for many reasons but so are people who say never use globals.
- 0
- 2018-02-18
- Joel M
-
- 2013-03-04
您的问题与php的工作方式有关.
以 $ wpdb 为例
$ wpdb 是一个众所周知的全局变量.
您知道何时将其声明并分配值吗?
是的,每次访问您的wordpress网站时,每个页面加载.
同样,您需要确保要声明的那些变量将被声明,并在每次加载页面时为其分配相应的值.
尽管我不是主题设计师,但我可以说after_setup_theme是一次钩子.它只会在激活主题时触发.
如果我是你,我将使用init或其他钩子.不,如果我是你,我根本不会使用全局变量...
我真的不擅长解释事物.因此,如果您想学习PHP,就应该读一本书.
Your question is involved with how php works.
Take $wpdb as example
$wpdb is a well-known global variable.
Do you know when it'll be declared and assigned with values ?
Every page loaded, yep, every time you visit your wordpress site.
Similarly, you need to make sure those variables that you want to be globalized will be declared and assigned with corresponding values every page loaded.
Although I'm not a theme designer, I can tell the after_setup_theme is one time hook. it'll only be triggered when theme activated.
If I were you, I'll use init or other hooks. No, if I were you, I won't use global variables at all...
I'm really not good at explaining things. So, you should pick up a book if you want to delve into PHP.
-
- 2015-11-25
您始终可以通过静态吸气剂使用单例模式.
<ul> <li><?php echo MyGlobals::get_nav_prop( 'proposal' )[ 'html' ]; ?></li> <li><?php echo MyGlobals::get_nav_prop( 'calvinball', 'html' ); ?></li> </ul> <?php if ( ! class_exists('MyGlobals') ): class MyGlobals { public $props; public function __construct(){ $this->props = array ( 'proposal' => array( 'title' => 'Proposal', 'text' => 'Proposal' ), 'calvinball' => array( 'title' => 'Calvinball', 'text' => 'Calvinball' ), ); } public function get_nav_prop ( $term, $prop = false ) { $o = self::instance(); if ( ! isset( $o->props[$term] ) ) { return falst; } if ( ! isset( $o->props[$term][ 'html' ] ) ) { $id = get_cat_ID( $term ); $link = esc_url ( get_category_link( $id ) ); $title = $o->props[$term]['title']; $text = $o->props[$term]['text']; $o->props[$term]['html'] = '<a href="'.$link.'" title="'.$title.'">'.$text.'</a>'; $o->props[$term]['link'] = $link; $o->props[$term]['id'] = $id; } if($prop){ return isset($o->props[$term][$prop]) ? $o->props[$term][$prop] : null; } return $o->props[$term]; } // ------------------------------------- private static $_instance; public static function instance(){ if(!isset(self::$_instance)) { self::$_instance = new MyGlobals(); } return self::$_instance; } } endif; // end MyGlobals
You can always use a singleton pattern via static getters.
<ul> <li><?php echo MyGlobals::get_nav_prop( 'proposal' )[ 'html' ]; ?></li> <li><?php echo MyGlobals::get_nav_prop( 'calvinball', 'html' ); ?></li> </ul> <?php if ( ! class_exists('MyGlobals') ): class MyGlobals { public $props; public function __construct(){ $this->props = array ( 'proposal' => array( 'title' => 'Proposal', 'text' => 'Proposal' ), 'calvinball' => array( 'title' => 'Calvinball', 'text' => 'Calvinball' ), ); } public function get_nav_prop ( $term, $prop = false ) { $o = self::instance(); if ( ! isset( $o->props[$term] ) ) { return falst; } if ( ! isset( $o->props[$term][ 'html' ] ) ) { $id = get_cat_ID( $term ); $link = esc_url ( get_category_link( $id ) ); $title = $o->props[$term]['title']; $text = $o->props[$term]['text']; $o->props[$term]['html'] = '<a href="'.$link.'" title="'.$title.'">'.$text.'</a>'; $o->props[$term]['link'] = $link; $o->props[$term]['id'] = $id; } if($prop){ return isset($o->props[$term][$prop]) ? $o->props[$term][$prop] : null; } return $o->props[$term]; } // ------------------------------------- private static $_instance; public static function instance(){ if(!isset(self::$_instance)) { self::$_instance = new MyGlobals(); } return self::$_instance; } } endif; // end MyGlobals
更新:我原来的问题已经解决,但这正变成关于为什么不使用全局变量的有效讨论,因此我正在更新问题以反映这一点.解决方法是
<?php global $category_link_prop; echo esc_url( $category_link_prop ); ?>
,如@TomJNowell建议.更新2:现在,我可以按照自己的意愿进行操作.但是我仍在使用全局范围,很乐意找到更好的方法.
我正在尝试为要在我的主题中各个地方使用的类别的永久链接设置一堆全局变量. 主要原因是要在主导航以及根据当前帖子所在类别选择的一系列子导航中使用.这不是我将要讨论的主题被释放以供他人使用,但是是为一个非常特定的目的而构建的.
这是我当前创建它们的方式(我只粘贴了一些变量).
我现在可以执行
<?php global $prop; echo $prop; ?>
将其移到4个地方,并取回代码的整个链接.当这种变化发生时,我只需要在一个地方进行更改.我愿意接受不涉及全球范围的替代方案.