Re: Manual unset and GC

From: Date: Tue, 11 Mar 2025 00:06:39 +0000
Subject: Re: Manual unset and GC
References: 1  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
Assuming that the variable gets created in the scope of the function
and that it never leaks outside of the scope (e.g. by reference), then
you can consider these things:

PHP will destroy the object when there are no more references to it in
the running script[1]. So, if the PDO object is limited to the
function's scope, unsetting the variable, setting it to something
else, or doing absolutely nothing will result in the same outcome. The
code line $stmt = null doesn't directly affect the PDOStatement that
was assigned to this variable previously. It just sets the value of
the variable to something else. https://3v4l.org/VP5IJ

Therefore, setting the variable to null as the last statement in the
function is just adding an extra unnecessary line of code. I assume
OPCache will optimize it away since it is dead code, but if not, then
that's just one more operation PHP has to do as part of the function.
From my testing, it seems the assignment is not optimized away. So
it's the opposite of an optimization.

The $stmt = null is cargo-cult programming[2]. Most likely, the
developer that came up with this guideline learned PHP years ago when
mysql_* API was in use. After switching to PDO, they realized there is
no close() method and, without understanding why, tried to come up
with an alternate "solution". Or maybe they've run into an issue with
out-of-sync operations on MySQL and saw setting the variable to null
as a quick solution. Later, people kept copying this code without
knowing why that line was there.

Neither the connection nor the statement should be closed. An attempt
to do so is a code smell that indicates that your code is poorly
designed and needs to be refactored. In your example, the refactoring
involves simply removing the dead-code assignment. In other cases, it
could mean restricting the objects only to the relevant scope. In my
opinion, there isn't any good reason to unset a variable.

[1]: https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.destructor
[2]: https://en.wikipedia.org/wiki/Cargo_cult_programming


Thread (5 messages)

« previous php.internals (#126707) next »