Yes, I know dependencies should be passed to the constructor. I'm not asking about coding styles or do's and dont's.
Many of the classes in my application are tied to an instance of a database driver class. For this I've created an abstract Factory class using PHP's late static binding. The only member of this class is a property to hold the driver's reference. It looks like this:
abstract class Factory {
static private $__instances;
static private $__default_driver;
protected $_driver;
static public function getInstance ( \Database\Driver $driver = null ) {
if ( ! isset($driver) ) {
if ( ! isset(self::$__default_driver) ) {
require ( \Core\Options::$database_driver[ 'path' ] );
self::$__default_driver = new \Core\Options::$database_driver[ 'class' ]( \Core\Options::$database_options );
}
$driver = self::$__default_driver;
}
$schema = $driver->getDatabase();
$class = get_called_class();
if ( ! isset(self::$__instances[ $schema ][ $class ]) ) {
self::$__instances[ $schema ][ $class ] = new $class( $driver );
self::$__instances[ $schema ][ $class ]->_driver = $driver;
}
return self::$__instances[ $schema ][ $class ];
}
}
As you can see, when I create an instance of the derived class, I pass an instance of the driver to its constructor. THEN set the property. I want to reverse this, if possible, by setting the property first then call the constructor. This way a derived class doesn't need to implement a constructor or worry about calling parent methods if it does.
I've looked into the Reflection
API to do this, but I can't seem to find anything that would work. Most Dependency Injection
links I found actually use the constructor. This needs to work on PHP 5.3.
For those who are adament that this is not possible, It can easily be done in PHP 5.4 using ReflectionClass::newInstanceWithoutConstructor()
.