Return In Constructor

ID

php.return_in_constructor

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

constructor, reliability

Description

Reports a return statement that yields a value from inside a class constructor (__construct). A constructor in PHP cannot return a result: new C() always evaluates to the newly created object, so any returned value is silently discarded.

Rationale

Because the language ignores the returned value, a return $something; inside __construct is dead code that misleads the reader into believing the constructor produces a meaningful result. It usually hides a logic mistake — for example, a guard clause that intended to abort object creation, or a method body that was pasted into the constructor by accident. A bare return; (an early exit with no value) is acceptable.

<?php
class Account
{
    private int $balance;

    public function __construct(int $balance)
    {
        if ($balance < 0) {
            return -1;             // FLAW — the value is discarded; the object is still created
        }
        $this->balance = $balance;
    }

    public function reset(): void
    {
        return;                    // OK — bare return is a plain early exit
    }
}

Remediation

Remove the value from the return. If the constructor needs to reject invalid input, throw an exception instead of returning a sentinel; if it needs to stop early, use a bare return;. Logic that genuinely produces a value belongs in a separate method or a static factory.