php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #63841 Mind the constructor return value
Submitted: 2012-12-23 16:20 UTC Modified: 2013-01-02 11:13 UTC
From: paxcoder+phpnet at gmail dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
 [2012-12-23 16:20 UTC] paxcoder+phpnet at gmail dot com
Description:
------------
As-is, returning values in the constructor has no effect, and the class instance 
is returned instead. Either allow for explicitly returned values to supersede the 
object, or warn about trying to return a value from a constructor.

Test script:
---------------
<?php
error_reporting(E_ALL|E_STRICT);
class C
{
    function __construct()
    {
        return NULL;
    }
}
$c = new C;
print_r($c);
?>


Expected result:
----------------
Either a warning at line 10, or $c set to NULL

Actual result:
--------------
No warning, and $c set to a C Object

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-12-30 15:45 UTC] krakjoe@php.net
-Status: Open +Status: Not a bug
 [2012-12-30 15:45 UTC] krakjoe@php.net
The job of a constructor is not to return a value but to construct an object, 
this is implicit in the implementation and associated keywords.

For example, one cannot call $var=stdClass::__construct(), because they are not, 
and cannot be static functions.

Making such a check is completely unnecessary and costly.

Not a bug.
 [2012-12-31 01:41 UTC] paxcoder+phpnet at gmail dot com
The check is useful to the programmer, and it should be possible to preform it 
statically.

As for the alternative - enabling returning arbitrary values - it could be 
convenient as well. However, I agree that it is unorthodox.

> Not a bug.

"My code doesn't have bugs, it has unexpected features."
 [2013-01-02 11:13 UTC] krakjoe@php.net
No you're code doesn't have bugs, or unexpected behavior. It is simply wrong.

As I said, a constructor's job is not to return a value but to construct an 
object: To implement a check to ensure it is being used correctly would cost 
every object that PHP ever constructs and would be detrimental and pointless.

Simply revise your code.
 [2013-01-04 13:52 UTC] paxcoder+phpnet at gmail dot com
For the record, I wholeheartedly disagree with your reasoning.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Dec 08 16:01:27 2024 UTC