Home > other >  Is there an easier way to do this with static variables?
Is there an easier way to do this with static variables?

Time:05-20

I have some old code where I took functions like this:

function getDataPlain() {
  $theArray = fetchFromDb("select * from tablename");
  return $theArray;
}

and converted them to use static like this:

function getDataStaticVersion() {
  static $theArray;
  if (isset($theArray)) {
    return $theArray;
  }
  else {
    $theArray = fetchFromDb("select * from tablename");
    return $theArray;
  }
}

Then, if the method was called more than once it would only hit the database once. This works well but I'm wondering if there's a cleaner way to do this with less code that has to be written in each function. (I have a number of functions like this that I'd like to convert to the static version)

CodePudding user response:

You can use the fact that the static variable is not set and null coalescing to load the value...

function getDataStaticVersion() {
  static $theArray;
  return $theArray ?? $theArray = fetchFromDb("select * from tablename");
}

So when it's not set it will run fetchFromDb().

As an alternative, you could restructure the code slightly so that rather than an earlier return, you call the extra code on when the array is set and always return at the end...

function getDataStaticVersion() {
  static $theArray;
  if (! isset($theArray)) {
    $theArray = fetchFromDb("select * from tablename");
  }

  return $theArray;
}
  •  Tags:  
  • php
  • Related