Last active
December 17, 2015 23:48
-
-
Save jamesrwhite/5691397 to your computer and use it in GitHub Desktop.
Lazy Loading Class Properties via Closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: