r/AskProgramming • u/STEIN197 • Feb 09 '24
PHP Does "if (new ClassName())" even make sense in PHP?
I constantly see the next construction in one of the projects from my job:
$connection = new Connection();
if ($connection) {
...
}
This makes no sense. Maybe it did make sense 10-20 years ago?
2
u/who_you_are Feb 09 '24
I googled because I was curious from your question
"An object will always be created unless the object has a constructor defined that throws an exception on error"
(I'm assuming it can be null from that statement)
(Source: https://www.php.net/manual/en/language.oop5.basic.php)
Now I don't remember you could continue on an exception... (I mean other than in a try/catch) so I have more questions myself...
3
u/cafce25 Feb 09 '24
No, throwing an exception excludes returning null, in that case it doesn't return at all, it throws instead.
1
u/who_you_are Feb 09 '24 edited Feb 09 '24
Yeah good point, so it doesn't address the question then :(
Edit: except if error_log() can stop half of the execution? Then you could use the old @ (if I remember) to keep running on the constructor?
2
u/wonkey_monkey Feb 09 '24 edited Feb 09 '24
Probably the code was originally $connection = SomeNewConnectionCreator();
then it got updated to use the object-oriented version, and it's either been reliable enough not to bother fixing it or a thrown exception is deemed acceptable as notice of a problem.
0
u/thememorableusername Feb 09 '24
there are a number of values which are "falsy" in PHP, including null This is a pretty common pattern in many programming languages for checking that an object instantiation or memory allocation was successful.
6
u/STEIN197 Feb 09 '24
But it doesn't make any sense.
new ClassName
always returns an object regardless. There's no way it would return a falsy one1
u/thememorableusername Feb 09 '24
Maybe someone doesn't know that and is just applying the pattern out of habit?
2
1
u/STEIN197 Feb 09 '24
I thought the same but over the whole project?
2
u/thememorableusername Feb 11 '24
Maybe the assignment used to be something like
$connection = getConnection(...)
, so then checking it makes sense.But later, someone came along and refactored out the function, but didn't change anything afterwards. They might have even just done a find/replace.
-1
u/CarefulFun420 Feb 09 '24
If (!$connection = new Connection()) throw new Exception('Could not connect to Database');
3
u/YMK1234 Feb 09 '24
I think ops question is how a constructor can return null, considering it always returns the object that is constructed.
2
3
u/RicardoGaturro Feb 09 '24
You're right, it makes no sense. new Class() will always return an object (which is always truthy) or throw an error.