DEV Community

Mohamed Said
Mohamed Said

Posted on • Originally published at divinglaravel.com

5

When does PHP call __destruct()?

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);
}

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more