FLX
FLX

Reputation: 2679

Store data in static property (php)

This seems to work how I want but I prefer ask before use it everywhere :

Let's say I have this class :

class A{

    static $data = null;
    public function getData(){
      if(isset(self::$data)) return self::$data;
      self::$data = // load sql data here
    }
}

Like some kind of singleton but in the function itself...

getData() can be called by external objects. I don't want data to be loaded more than one per page load.

I did some cheap benchmark and look like it works exactly how I want.

Do you think it's a bad practice ?

Upvotes: 0

Views: 58

Answers (1)

Okneloper
Okneloper

Reputation: 1283

There will be arguments about whether this is bad practice or not. If you store the data in a static variable though, I would suggest making the getData() method static as well. And the $data should be set to either private pr public. So it would be:

class A {

static protected $data = null;
static public function getData(){
  if(isset(self::$data)) return self::$data;
  self::$data = // load sql data here
}

}

And don't forget to return the data after you load it as well.

Upvotes: 1

Related Questions