Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Returning a value from a constructor is deprecated

Description

new X always evaluates to the newly created instance, no matter what __construct() returns: any value returned from a constructor is discarded.

Since explicitly returning a value from __construct() is therefore always misleading dead code, PHP 8.6 deprecates it. A bare return; with no expression, used purely to exit the constructor early, remains unaffected.

Example

<?php

class X {
    public function __construct() {
        return 42;
    }
}

$x = new X;
var_dump($x);

?>

Literal Examples

  • Returning a value from a constructor is deprecated

Alternatives

  • Use a bare return; (with no expression) to exit the constructor early.
  • If you need to build and hand back an object based on some logic, use a static factory method instead of relying on new and a constructor return value.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See constructorReturnDeprecated