how can i access the second property or method in this statement
$this->test->hello();
In my __get()
I can only figure out how to figure out what the test
property is. I want to be also be able to capture the 'hello' method call. and do some dynamic things with it.
So in short if I type
$this->test->hello()
I want to echo
each segment
echo $propert // test
echo $method //hello
The issue is that my test is being used to instantiate a new class object from an outside class. The method hello
belongs to the test
class object.
I want to capture the method within my __get()
.
How can i do this?
EDIT:
public function __get($name)
{
if ($name == 'system' || $name == 'sys') {
$_class = 'System_Helper';
} else {
foreach (get_object_vars($this) as $_property => $_value) {
if ($name == $_property)
$_class = $name;
}
}
$classname = '\\System\\' . ucfirst($_class);
$this->$_class = new $classname();
//$rClass = new \ReflectionClass($this->$_class);
$rClass = get_class_methods($this->$_class);
foreach($rClass as $k => $v)
echo $v."
";
//print_r($rClass);
return $this->$_class;
It seems you are after some kind of proxy class, this might suit your needs.
class ObjectProxy {
public $object;
public function __construct($object) {
$this->object = $object;
}
public function __get($name) {
if (!property_exists($this->object, $name)) {
return "Error: property ($name) does not exist";
}
return $this->object->$name;
}
public function __call($name, $args) {
if (!method_exists($this->object, $name)) {
return "Error: method ($name) does not exist";
}
return call_user_func_array(array($this->object, $name), $args);
}
}
class A {
public $prop = 'Some prop';
public function hello() {
return 'Hello, world!';
}
}
class B {
public function __get($name) {
if (!isset($this->$name)) {
$class_name = ucfirst($name);
$this->$name = new ObjectProxy(new $class_name);
}
return $this->$name;
}
}
$b = new B();
var_dump($b->a->hello());
var_dump($b->a->prop);
var_dump($b->a->foo);
var_dump($b->a->bar());
Output:
string 'Hello, world!' (length=13)
string 'Some prop' (length=9)
string 'Error: property (foo) does not exist' (length=36)
string 'Error: method (bar) does not exist' (length=34)
Example:
It could be easily extend for other magic methods like __set
, __callStatic
, __isset
, __invoke
, etc.
I think you want to use __call
instead of __get
. Also, don't.
The object you instantiated for $this
will use the __get
magic method to create the object (as a property) test
. The object stored at $this->test
needs to implement the __call
magic method to use hello()
if it's not defined