<?php
class Super {
public $my;
public function __construct ( $someArg ) {
if ( class_exists('Sub') ) { // or some other condition
return new Sub( $someArg );
}
$this->my = $someArg;
}
}
class Sub extends Super {}
?>
This doesn't work, as new Super()
will be an "empty" Super
object (all members are NULL
). (PHP doesn't allow assignments to $this
, so $this = new Sub()
doesn't work either).
I know the correct pattern would be a factory here. But that would require a lot of changes in the code, so I'm wondering whether it's possible to do it this way. Since Sub
is-a Super
, I don't see why it shouldn't be restricted from an OOP point of view.
You got something wrong here. The constructor does not have a return value, you cannot return an instance from the constructor - once the constructor is called, the class is settled, you cannot change it any more.
What you want to do is to implement the factory pattern for this:
Use PHP reflection. No need for switches or inheritance when you're using a factory.
You can't assign to
$this
and you cannot return anything from a constructor.