Friday, September 21, 2007

PHP's static keyword

I quite like PHP's static keyword (C has the same thing). It lets you create a persistent variable that is local to a function, without having to add an instance variable. Useful for lazy loading:

private function getInvitation() {
static $invitation = null;
if (! $invitation) {
... create invitation ...
$invitation = ...;
}
return $invitation;
}

4 comments:

  1. I have far more experience in C/CPP than PHP, so maybe PHP handles it differently. But on a web server which is potentially serving many pages at the same time, this example strikes me as a very good example of what *not* to do without some sort of sync/lock mechanism.
    While one requests creates the invitation, another one can go in, see that there's still no invitation, and start to create it again... No?

    ReplyDelete
  2. Hi Yaron - Actually there's nothing to worry about in this case - the scope of the variable is limited to the request. In other words, the local variables in different requests are totally independent - we're not writing to disk or to shared memory or anything like that. The variables are just temporary.

    ReplyDelete
  3. Ah, OK.
    Makes sense. Thanks for the clarification.

    ReplyDelete
  4. No probs! I love Ruby on Rails, but the more I use PHP the more I come to love its many conveniences - not the least of which is its huge library of built-in functions.

    ReplyDelete