0

The use of the static $var in this function works, but I'm wondering if there's a more efficient way to handle a situation like this.

function static_test() {
    static $var = FALSE;
    if ( ! $var) $var = date('Ymd');
    // do some stuff with $var
}

I wondered if possible to do something closer to this... or other to declare the static $var.

function static_test() {
    static $var = date('Ymd');
    // do some stuff with $var
}

How would you do it?

6
  • 4
    What are you actually trying to achieve? Commented Dec 27, 2011 at 0:34
  • I think this is a good read for you php.net/manual/en/language.variables.scope.php, specificaly where it talks about static variables search for "Using static variables" on the page, you can't declare a static variable with an expression it even has some nice examples Commented Dec 27, 2011 at 0:47
  • I can't think of a better, or more clear way to explain it than in the second example above. I wondered if there might be a way to declare a static var with the value of a function. I know it can be done something like the first example. Commented Dec 27, 2011 at 0:47
  • 2
    No, static variables can only be assigned values that are not the result of expressions Commented Dec 27, 2011 at 0:48
  • @rroche, thanks. So you'd also do it like the first example then? Commented Dec 27, 2011 at 0:50

2 Answers 2

1

The second option is almost fine. As you may read here: http://www.php.net/manual/en/language.variables.scope.php,

...[a static variable] is initialized only in first call of function...

So there is no need for this piece of code: if ( ! $var) $var = date('Ymd');

However, you need a dummy:

$dummy=date('Ymd'); static $var=$dummy;

Sign up to request clarification or add additional context in comments.

3 Comments

thanks @Alfredo for taking the time to answer the question with an option that works, instead of downvoting and leaving a non-constructive comment.
Did you test the $dummy initialization of $var ? I have my doubts as it specifically states not liking expressions on the values,
@rroche, I didn't test it. Since this question was being downvoted I didn't bother further. I resolved that my 1st example that worked would be the way I continue to code it if I need a static var in a function.
0

The second example is simply not in php syntax. I loathe static var usage at all, but especially in this instance. I would use a class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.