Jon Aquino's Mental Garden

Engineering beautiful software jon aquino labs | personal blog

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;


  • 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?

    By Anonymous Yaron, at 9/24/2007 3:26 a.m.  

  • 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.

    By Blogger Jonathan, at 9/26/2007 7:10 p.m.  

  • Ah, OK.
    Makes sense. Thanks for the clarification.

    By Anonymous Yaron, at 10/01/2007 3:36 a.m.  

  • 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.

    By Blogger Jonathan, at 10/01/2007 10:05 p.m.  

Post a Comment

<< Home