DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Inheritance in PHP: A Simple Guide With Examples
  • Writing DTOs With Java8, Lombok, and Java14+
  • Graph API for Entra ID (Azure AD) Object Management

Trending

  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  1. DZone
  2. Coding
  3. Languages
  4. PHP: Don’t Call the Destructor Explicitly

PHP: Don’t Call the Destructor Explicitly

By 
Stoimen Popov user avatar
Stoimen Popov
·
Nov. 15, 11 · Interview
Likes (1)
Comment
Save
Tweet
Share
17.9K Views

Join the DZone community and get the full member experience.

Join For Free

“PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++”[1] says the documentation for destructors, but let’s see the following class.

class A
{
	public function __construct()
	{
		echo 'building an object';
	}
 
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();

Well, as you can not call the constructor explicitly:

$obj->__construct();

So we should not call the destructor explicitly:

$obj->__destruct();

The problem is that I’ve seen this many times, but it’s a pity that this won’t destroy the object and it is still a valid PHP code.

PHP destructors can't be called explicitly!

PHP destructors cannot be called explicitly!

Constructors and destructors in PHP are part of the so called magic methods. Here’s what the doc page says about them.

The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.


To be more precise let’s take a look of the definition of destructors.

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.


What if I Call the Destructor Explicitly?

Let’s see some examples!

class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();
 
// prints hello world
echo 'hello world';
 
// PHP interpreter stops the script execution and prints
// 'destroying the object'

This is actually a normal behavior. At the end of the script the interpreter frees the memory. Actually every object has a built-in destructor, just like it has built-in constructor. So even we don’t define it explicitly, the object has its destructor. Usually this destructor is executed at the end of the script, or whenever the object isn’t needed anymore. This can happen, for instance, at the end of a function body.

Now if we call the destructor explicitly, which as I said I’ve seen many times, here’s what happens.

class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();
 
// this is valid and it prints 'destroying the object'
// BUT IT DOES NOT DESTROY THE OBJECT
$obj->__destruct();
 
// prints hello world
echo 'hello world';
 
// HERE PHP ACTUALLY DESTROYS THE $obj OBJECT
// ... and again prints 'destroying the object'

As you can see calling the destructor explicitly doesn’t destroy the object. So the question is …

How to Destroy an Object Before the Script Stops?

Well, to destroy an object you can assign a NULL value to it.

class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();
 
// prints 'destroying the object'
$obj = null;
 
// prints 'hello world'
echo 'hello world';
 
// the script stop its execution

Caution

Be aware that if you don’t clone the object $obj, and simply assign it to another variable, then $obj = null will be pointless. Let’s see the following example.

class A 
{
	public function printMsg()
	{
		echo 'I still exist';
	}
 
	public function __destruct()
	{
		echo 'destroying the object';
	}
 
}
 
$obj = new A();
 
// $newObj is pointing to $obj
$newObj = $obj;
 
// this doesn't destroy $newObj
// as it appears both $obj and $newObj point to the same memory
// so PHP doesn't free this memory
$obj = null;
 
// prints 'i still exist'
$newObj->printMsg();
 
// prints 'hello world'
echo 'hello world';
 
// now the scripts destroys the "object", which in this
// case is $newObj and prints 'destroying the object'

This example shows us that actually assigning NULL to an object doesn’t quite destroy it if there are another objects pointing to the same memory.

class A 
{
	public function printMsg()
	{
		echo 'I still exist';
	}
 
	public function __destruct()
	{
		echo 'destroying the object';
	}
 
}
 
$b = new A();
 
$d = $c = $b;
 
$b = null;
 
$c->printMsg();
$d->printMsg();
 
// prints 'destroying the object' ONLY ONCE

In this last example there are two interesting things to note. First $b = null doesn’t call the destructor, and at the end of the script there’s only one implicit call of the destructor, although there are two objects.

Conclusion

The important thing to note is that you shouldn’t call the destructor of an object explicitly! Not because it will throw an fatal error, but simply because it won’t destroy the object.

[1] PHP: Constructors and Destructors

Related posts:

  1. Some Notes on the Object-oriented Model of PHP
  2. Construct a Sorted PHP Linked List
  3. Object Cloning and Passing by Reference in PHP

Source: http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/
PHP Destructor (computer programming) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Inheritance in PHP: A Simple Guide With Examples
  • Writing DTOs With Java8, Lombok, and Java14+
  • Graph API for Entra ID (Azure AD) Object Management

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!