4

I have been trying to work out the most effecient way to use functions in WordPress.

I have a big slow function big_slow_function() that ideally is only run once. But I need to use the boolean that is returned by this function throughout my theme files (in header.php, page.php, sidebar.php, footer.php, loop-page.php, functions.php etc).

I am wondering how to do this.

I tried putting this in my functions.php to try and avoid calling big_slow_function() more than once:

global $my_important_boolean;

function $get_my_important_boolean()
{
    global $my_important_boolean;

    if ($my_important_boolean == NULL) // if big_slow_function() has not been run yet
        $my_important_boolean = big_slow_function();

    return $my_important_boolean;
}

And then I put code like this throughout my theme files:

if ($get_my_important_boolean()) {
    // customize content to user
}

But the big_slow_function() is still being run every time. I am not sure what I am doing wrong and have found it hard to find good documentation on variable scope in WordPress. Perhaps I need to pass a reference/pointer to the variable?

Any help with this problem is much appreciated as I have been struggling with it for sometime.

  • Close-voted as off-topic. This is a PHP/general-programming question, not a WordPress question. – Chip Bennett Mar 15 '12 at 12:53
  • Apologies. I thought the problem had to do with the way Wordpress handled global variables. I was wrong. – Ben Pearson Mar 16 '12 at 5:21
  • @ChipBennett If you close vote, then you should actually click the vote link. – kaiser Oct 3 '12 at 13:24
  • @kaiser I disagree. A downvote says that the question itself is bad/low-quality. A close-vote for being off-topic simply indicates that the question belongs elsewhere. – Chip Bennett Oct 3 '12 at 20:31
  • @ChipBennett I wrote close vote, not down vote... Didn't do that either, right? :) – kaiser Oct 4 '12 at 6:32
13
function my_big_function() {

    static $result;

    // Function has already run
    if ( $result !== null )
        return $result;

    // Lot of work here to determine $result
    $result = 'whatever';

    return $result;
}

Also see: https://stackoverflow.com/questions/6188994/static-keyword-inside-function

  • Perfect. Exactly what I was looking. Much appreciated, Geert. – Ben Pearson Mar 16 '12 at 5:19
  • Just to complement this answer, and also because I don't see any reference to this in any of the comments, PHP functions cannot begin with the $ as that is reserved for $variables in PHP. – DaveyJake Mar 18 '17 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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