Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lazy load public class data member in PHP

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.

like image 515
user4o01 Avatar asked Oct 30 '25 10:10

user4o01


1 Answers

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.

like image 87
meagar Avatar answered Nov 02 '25 01:11

meagar