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.

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.

share|improve this question
    
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
show 5 more comments

1 Answer 1

up vote 3 down vote accepted
function my_big_function()
{
    static $result;

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

    // Lot of work to determine $result

    $result = TRUE;
    return $result;
}

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

share|improve this answer
    
Perfect. Exactly what I was looking. Much appreciated, Geert. –  Ben Pearson Mar 16 '12 at 5:19
add comment

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.