Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unset useful?

Tags:

php

I never ever saw someone using unset and I was wondering if that saves something or if it is a completely waste of time and code?

<?php
$message = "Line 1\r\nLine 2\r\nLine 3";
mail('[email protected]', 'My Subject', $message);

/* IS THERE ANY REASON TO UNSET $message ? */
unset($message);
?>
like image 780
Adward Smith Avatar asked Nov 30 '22 20:11

Adward Smith


1 Answers

It depends.

If you're developing a long-running daemon or job, unset() can be used to keep memory in reasonable bounds: to help prevent leaks.

If you're developing a page/script for a web application, unset() isn't terribly useful for memory management.

And in either case, it's useful if you're relying on arrays and you need to remove a value. A silly example, perhaps ... but consider something like this:

$users = getUsers($someCondition);
foreach ($users as $k => $v) {
  unset($users[$k]['password_hash']);
}
print json_encode($users);

In the specific example you've given, it's useless:

<?php
$message = "Line 1\r\nLine 2\r\nLine 3";
mail('[email protected]', 'My Subject', $message);

// PHP is about to clean everything up anyway ... don't bother doing this:
unset($message);
?>
like image 189
svidgen Avatar answered Dec 04 '22 03:12

svidgen