I want to lazy load the public data members of a class in PHP. Assume we have the following class:
<?php
class Dummy
{
    public $name;
    public $age;
    public $status_indicator;
}
?>
If $name, $age and $status_indicator were private data members I would lazy load them via their getter methods, but since they are public - I am unclear as to how to lazy load them. Is this possible?
EDIT:
Someone commented that there is a method called __get which might help to solve this issue, but I didn't understand it.
You can use __get to simulate public members which are really dynamically loaded on first access. When you attempt to access an undefined member of an object, PHP will invoke __get and pass it the name of the member you attempted to access. For example, accessing $x->my_variable would invoke __get("my_variable") if the class had defined an __get_ method.
In this example, $dummy->name indirectly invokes the getter method getName, which initializes a private member named $_name on first access:
<?php
class Dummy
{
  private $_name;
  public function __get($var) {
    if ($var == 'name') {
      return $this->getName();
    } else if ($var == 'age') {
      // ...
    } else {
      throw "Undefined variable $var";
    }
  }
  public function getName() {
    if (is_null($this->_name)) {
      // Initialize and cache the value for $name
      $this->_name = expensive_function();
    }
    return $this->_name;
  }
}
$dummy = new Dummy();
echo $dummy->name;
You could similarly define and invoke other accessors like getAge.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With