Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

One Wordpress function I happen to use frequently is get_template_directory_uri(). While I tried to minimize or avoid its use where I can, I still happen to have more than one call to this function in certain pages across my theme. Most of the time in a series of href or inside other functions (for which I normally put the URI resulting from get_template_directory_uri() in a $variable - however I still find that I might have to store again that variable in a different php file).

I wonder, would it be best if I store the returning value (my theme URI) in a global and use echo the global when I need it in different parts of my theme php files?

I'm still learning my way to best practices and uses of variables and globals.

Thank you

share|improve this question
    
This is more of a PHP question then a WordPress question, and really should be asked on Stack Overflow. –  bungeshea Jan 2 '13 at 3:33
1  
This does not seem off topic to me. My preference is to just use the function as is where necessary along with its sister function get_stylesheet_directory_uri(). –  Joseph Jan 2 '13 at 4:38
    
It seems to be about using functions vs variables/constants –  bungeshea Jan 2 '13 at 6:01

2 Answers 2

up vote 1 down vote accepted

I would stay stick to the function. PHP caches functions for speed and efficiency. In some situations, using a function is faster then using a variable.

There are other benefits too - imagine if you changed the name of your variable - you would have to go and update every piece of code where it's used.

share|improve this answer

Global variables are hard to debug, because you cannot see easily where they are set or changed. And especially in WordPress, which suffers from too many globals already, collisions might happen, because plugin developers forget to prefix everything or they choose the same prefix as you did by accident.

Using an existing function name results in an error everyone can see and fix immediately. Using an existing global variable will silently change your code in unexpected ways.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.