On 10 March 2025 16:15:16 GMT, Vinicius Dias <carlosv...@gmail.com> wrote:
>Hello, folks. If this is not the correct place to ask, I apologize.
>
>> TL;DR: Does setting a variable to `null` (or even `unset`ing it) have 
>> **any** effect if that's the last instruction of a function?
>
>The full version of the question with context:
>
>I have a question about the inner workings of PHP that was raised by
>some people at work.
>
>In the code we write at the company I work for, there's a guideline to
>always assign `null` to the variables of type `PdoStatement`.
>Something like the following:
>
>```
>$stm = null;
>```
>
>I understand this removes the reference to the object, calls the
>destructor and frees the memory, but the point is: the guideline
>mandates that we do that even if it is the last instruction of a
>function, for example:
>
>```
>function example(): void
>{
> // run your SQL queries
>
> $stm = null;
>}
>```
>
>I understand that this last line is not needed and removing it would
>have literally no effect on the code execution since `$stm` will go
>out of scope and the same things (remove reference, call destructor
>and free memory) will happen exactly the same.
>
>While discussing this with a few colleagues it was pointed out that
>**maybe** PHP will execute the GC immediately when we do `$stm = null`
>but not when the variable goes out of scope, making the explicit null
>as some sort of optimization.
>
>I didn't find any resources on the documentation that could point to
>which assumption is correct, so I post the question here:
>
>Does setting a variable to `null` (or even `unset`ing it) have **any**
>effect if that's the last instruction of a function?
>
>Thank you

No.

It has no effect. At the end of the function PHP would remove a ref to the 
variable anyway. Setting it to null first is an action that will take time, 
unless opcache is turned on and realises it's a useless action.

cheers
Derick

Reply via email to