Skip to content

Instantly share code, notes, and snippets.

@jamesrwhite
Last active December 17, 2015 23:48
Show Gist options
  • Save jamesrwhite/5691397 to your computer and use it in GitHub Desktop.
Save jamesrwhite/5691397 to your computer and use it in GitHub Desktop.
Lazy Loading Class Properties via Closures
<?php
class view_abstract {
protected $_data = array();
public function __get($name) {
echo "Getting $name\n";
if (is_callable($this->_data[$name])) {
$this->_data[$name] = $this->_data[$name]->__invoke();
}
return $this->_data[$name];
}
public function __set($name, $value) {
echo "Setting $name\n";
$this->_data[$name] = $value;
}
}
class controller_abstract {
public function __construct() {
$this->view = new view_abstract;
$this->view->b = function() {
echo "LOADING SOME DATA OR WHATEVER\n";
return 1;
};
}
}
class g_controller extends controller_abstract {
public function __construct() {
echo "Hi I'm " . __CLASS__ . "\n";
parent::__construct();
var_dump($this->view->b);
}
}
class c_controller extends controller_abstract {
public function __construct() {
echo "Hi I'm " . __CLASS__ . "\n";
parent::__construct();
}
}
new c_controller;
new g_controller;
@jamesrwhite
Copy link
Author

Output:

» php closure.php
Hi I'm c_controller
Setting b
Hi I'm g_controller
Setting b
Getting b from
LOADING SOME DATA OR WHATEVER
int(1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment