PHP ReflectionClass calls destructor even when constructor throws exception

I am getting strange behavior since PHP 5.4 here. Suppose the following code:

class ExceptionDuringConstruction
{
    public function __construct() {
        echo '<br />construct before exception';
        throw new Exception('construction failed');
        echo '<br />construct after exception'; // unreachable, just checking
    }

    public function __destruct() {
        echo '<br />destruct';
    }
}

$reflection = new \ReflectionClass('ExceptionDuringConstruction');
$instance   = $reflection->newInstance();

      

The above code prints:

construct before exception
destruct

      

This can't be right or am I missing something? If I do the same using NEW everything works as expected, no Destructor is called. It looks like a mistake to me - any opinions? Is this known (found nothing on it)?

PS: Since this is my first question here, but I've been reading for a long time - thanks for this wonderful site! It almost always likes it: Google> Stackoverflow> Solution wit Explanation :-)

+3


source to share





All Articles