I have an autoloader, initializing alot of objects as a mini-framework is loaded. The objects are saved as static variables, but now I've run into a problem. I have a file which is instantiated in the autoloader, but used later kind of like an exception handler, taking care of special cases when called. The intention is that the methods within this class returns $this, the class object, but when doing so, the returned value is not an instance of the called object, but gets inherited into the class which calls it. Furthermore the called exception_handler is not only an instance of itself, but everything instanziated throughout the entire autoloader, inheriting $this as everything gets loaded. Confusing but I've built a small example:
class a {
public $a_tmp = 'tmp';
}
class b extends a {
public $b_tmp = 'tmp';
public function getOnlyThisClass() {
return $this;
}
}
$b = new b();
$b->getOnlyThisClass();
This returns:
object(b)#1 (2) {
["b_tmp"]=>
string(3) "tmp"
["a_tmp"]=>
string(3) "tmp"
}
And I need it to return ONLY the called class when special methods are called. I know this can be fixed with a factory pattern, but would like to avoid it in this case.
Thanks.
Try to use Reflection to get class object properties without inherited properties:
<?php
class a {
public $a_tmp = 'tmp';
}
class b extends a {
public $b_tmp = 'tmp';
public function getOnlyThisClass() {
$cl = new stdClass();
$refclass = new ReflectionClass($this);
foreach ($refclass->getProperties() as $property)
{
$name = $property->name;
if ($property->class == $refclass->name) {
$cc = $property->name;
$cl->$cc = $this->$name;
}
}
return $cl;
}
}
$b = new b();
var_dump($b->getOnlyThisClass());
Output:
object(stdClass)#2 (1) { ["b_tmp"]=> string(3) "tmp" }
You can create an stdClass and assign found properties there.. Finish this to match your needs.