Req #78313 [Opn]: Return from constructor should trigger an error or warning

From: Date: Fri, 19 Jul 2019 18:03:57 +0000
Subject: Req #78313 [Opn]: Return from constructor should trigger an error or warning
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-221861@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=78313&edit=1 ID: 78313 Updated by: girgias@php.net Reported by: php-bugs at allenjb dot me dot uk -Summary: return from constructor should trigger an error or warning +Summary: Return from constructor should trigger an error or warning Status: Open Type: Feature/Change Request Package: Class/Object related -Operating System: n/a +Operating System: -PHP Version: 7.3.7 +PHP Version: Next major version Block user comment: N Private report: N New Comment: I think there was some talk/PR to do something about calling magic methods directly which includes the constructor, destructor, __clone(), __isset() and other. I do agree that it should do something but that would probably need an RFC from my understanding. Previous Comments: ------------------------------------------------------------------------ [2019-07-19 17:24:55] php-bugs at allenjb dot me dot uk Description: ------------ It's currently possible to write a constructor that returns a value, but there is no way (as far as I can tell) to retrieve this value when constructing an object. Technically you can call the constructor directly, but this is not normally done in the course of object construction (other than calling the parent constructor). While to experienced developers, the fact that you should/cannot return a value from a constructor seems obvious, this is not always so to newbies - https://old.reddit.com/r/webdev/comments/cf9l3h/working_php_code_working_on_a_test_server_isnt/ While thorough testing would obviously reveal this issue in the above case, we all know that not everyone, especially newbies, thoroughly test their code. In the above case the issue isn't obvious until an error in the curl query occurs, but all the user ends up with is an improperly constructed object - even if their code at the point of construction checks for a string value rather than an object, this check will never trigger. Attempting to declare a return type already triggers an error: https://3v4l.org/rsikK Test script: --------------- <?php class Foo { public function __construct() { return "bar"; } } $foo = new Foo(); var_dump($foo); Expected result: ---------------- Error / warning that constructors cannot return a value Actual result: -------------- object(Foo)#1 (0) { } ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=78313&edit=1

« previous php.bugs (#221861) next »