Get magic method
All magic methods must be declared public.
class A
{
public function __get($var)
{
return 2;
}
}
$a = new A();
echo $a->foo; // 2
You can keep track of variables which are not defined inside the class.
class myController
{
private $_modelBroker = array();
public function __get($var)
{
if (strstr($var, 'model')) {
$modelKey = substr($var, 5);
if (in_array($modelKey,
array_keys($this->_modelBroker))) { // registered
return $this->_modelBroker[$modelKey];
} else { // not registered
eval('$model = new Model_'.$modelKey.'();');
$this->_modelBroker[$modelKey] = $model;
return $model;
}
}
}
}
class Model_Number
{
public $id = 123;
}
$controller = new myController();
echo $controller->modelNumber->id; // 123
// _get is called, because modelNumber is undefined
The function names bellow are magical in PHP classes.
__construct(), __destruct(),
__call(), __callStatic(),
__get(), __set(),
__isset(), __unset(),
__sleep(),
__wakeup(),
__toString(),
__invoke(),
__set_state(),
__clone()
__debugInfo()
Last update: 382 days ago