Call a function when I access a property (PHP magic methods) -
basically i'm using php overloading create dynamic methods , properties. want trigger function property access keeping access methods.
in other terms, that's php code:
first class:
class _class { private $_instance; public function __construct() { $this->_instance = new _object(); } public function __get($name) { switch ($name) { case "instance": //logics break; } return null; } }
second class:
class _object { public function __call($method, $args) { switch ($method) { case "method": //logics break; } return null; } }
now want execute function when access object property in way:
$obj = new _class(); echo $obj->instance; //some output here, executing function echo $obj->instance->method(); //different output, executing method of instance
thanks, appreciated!
when instantiate first class, create $this->_instance
instead $obj->instance
. so $obj->instance
null
, can not call on that.
but, if try $obj->_instance->method();
, bad also, because _instance
private. need add getter. try this:
class _class { private $_instance; public function __construct() { $this->_instance = new _object(); } public function __get($name) { switch ($name) { case "instance": echo "instance"; break; } return null; } public function getinstance() { return $this->_instance; } } class _object { public function __call($method, $args) { switch ($method) { case "method": echo "method"; break; } return null; } } $obj = new _class(); $obj->instance; $obj->getinstance()->method();
output is:
instance method
Comments
Post a Comment