Search code examples
phpunset

Should i use unset inside a function?


Is there any purpose to unset $data? Should i unset it if it contains large data?

<?php
require 'db.php';
class Test{
    public $id = 0;
    public $name;
    public function __construct()
    {
        $this->getUserInfo();
        echo $this->name;
    }
    private function getUserInfo()
    {
        global $db;
        $query = $db->prepare('SELECT id,name FROM users WHERE group = :g LIMIT 1');
        if ($query->execute(array('g' => 'admin')))
        {
            $data = $query->fetch(); // <--
            $this->id = $data[0];
            $this->name = $data[1];
            return true;
        }
    }
}
(new Test);
?>

Solution

  • There's no need. When the function returns, the variable goes away by itself.

    And even if you do unset it, you still have references to the values that it contained in $this->id and $this->name, so their memory won't be reclaimed. The only memory you'll reclaim is the tiny array object that points to them.

    PHP doesn't make copies when you do assignments. Strings and numbers are immutable, so there's no need to copy them. Objects are copied by reference. And arrays use copy-on-write technology, so it only copies them later if the old reference still exists and you then modify the copy.