<?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 can’t assign to
$thisand you cannot return anything from a constructor.