I was working on an abstract class to save on some code for a couple of classes. These classes are all factories that instantiate themselves through different static calls. I could save some code by putting all those methods in an abstract class.
However, I ran into a late static binding problem... since our web host isn't using 5.3 or later, I don't have access to get_called_class. If I have
$class = __CLASS__;
return new $class();
in the abstract class, __CLASS__
is the name of the abstract class, when I actually want it to use the called class.
I've seen examples of abstract factories on the web where the child classes have their own instantiation methods, and don't rely on the abstract parent for it. However, in this situation, the only reason for the abstract class is to save code, so if I can't do it there, the value of it diminishes greatly.
Is there a workaround in php < 5.3? debug_backtrace()
?
Edit:
I did a test and it seems debug_backtrace()
will not work! I guess this is why we need late static binding.
<?
abstract class abstractFactory {
public function create() {
print_r(debug_backtrace());
$class = __CLASS__;
return new $class();
}
}
class concreteFactory extends abstractFactory {}
$chimborazo = concreteFactory::create();
and the result:
$ php test.php
Array
(
[0] => Array
(
[file] => /var/www/test.php
[line] => 13
[function] => create
[class] => abstractFactory
[type] => ::
[args] => Array
(
)
)
)
Fatal error: Cannot instantiate abstract class abstractFactory in /var/www/test.php on line 7