Laravel Queues in Action (2nd edition) is now available!

When does PHP call __destruct()?

Updated: Feb 18, 2020 — 1 min Read#quick-dip

In PHP, __construct() is called while creating an object and __destruct() is called while the object is being removed from memory. Using this knowledge, we can create more fluent APIs as demonstrated by Freek Van der Herten in this short video.

Now let's see when PHP calls __destruct() exactly.

An object is removed from memory if you explicitly remove it:

$object = new Object();

unset($object); // __destruct will be called immediately.

$object = null; // __destruct will be called immediately.

It's also called when the scope where the object live is about to be terminated, for example at the end of a controller method:

function store(Request $request)
{
   $object = new Object();
  
   User::create(...);

   // __destruct will be called here.

   return view('welcome');
}

Even if we're within a long running process, queued job for example, __destruct will be called before the end of the handle method:

function handle()
{
   $object = new Object();
  
   User::create(...);

   // __destruct will be called here.
}

It'll also be called when the script is being terminated:

function handle()
{
   $object = new Object();

   User::create(...);

   // __destruct will be called here.

   exit(1);
}

Hey! 👋 If you find this content useful, consider sponsoring me on GitHub.

You can also follow me on Twitter, I regularly post about all things Laravel including my latest video tutorials and blog posts.

By Mohamed Said

Hello! I'm a former Laravel core team member & VP of Engineering at Foodics. In this publication, I share everything I know about Laravel's core, packages, and tools.

You can find me on Twitter and Github.

This site was built using Wink. Follow the RSS Feed.