When object property is asked first time gets data, and then just returns it - is it possible?
I need some data from the object.
I don't want these data to be loaded in class construction, because it is db heavy. I don't want to load it more than once in a page. I don't want to remember was it loaded already, or not.$object->data // should be loaded in construction
$data = $object->get_data() // ok, but I need to remember was is got开发者_C百科 already, or not.
Is there a way to use $object->data
, if it is asked first time, it actually gets data and returned it. And when I ask it after this, it just returns old data.
$data = $object->get_data()
. But maybe I'm missing something.This is usually solved using "lazy loading" - the property itself is backed using a private field, which gets initialized to some magic value (e.g. null
) in the constructor, and gets filled the first time the getter gets called. After that, the getter returns the already-loaded value. Example:
class Foobar {
private $_lazy;
public function __construct() {
$this->_lazy = null;
}
public function __get($key) {
switch ($key) {
case 'lazy':
if ($this->_lazy === null)
$this->loadLazy();
return $this->_lazy;
}
}
private function loadLazy() {
$this->_lazy = rand();
}
}
Thing that you talking about is called Lazy Loading. You should implement that in method get_data(). If you wanna use it as property, not method, you must use PHP's magic __get
method and return your data when accessing that data
property.
But I recommend using method - it's more explict.
Well, you can do this
//create an object
class Foo{
//give some attributes
public $attr1;
public $attr2;
public $attr3;
public $attr4;
....
....
//create a function to load data
public function foofunction()
{
//and set the attrs
$this->attr1 = $somevalue;
$this->attr2 = $somevalue;
$this->attr3 = $somevalue;
//...
....
}
}
and you in your page
//create an object
$foo = new Foo();
//fetch data which will instantiate the attrs
$foo->foofunction();
//and you can use any attr at any time
echo $foo->attr1;
echo $foo->attr2;
//and this attr necessarily does not have to string, or int or ..
//it can be anything
Object has a property - flag, that indicates if the data have been asked before.
It's lazy loading
// simple implementation
public function get_data() {
if (is_null($this->_data)) {
$this->_data = $db->query();
}
return $this->_data;
}
精彩评论