Home arrow PHP arrow Page 2 - Understanding Destructors in PHP 5

Building a Sample - PHP

Despite the scary-sounding name, destructors aren't evil. Indeed, their use is often necessary to help keep your applications running properly. This article, the first part of a five-part series, introduces you to destructors and their use with PHP 5 programs.

  1. Understanding Destructors in PHP 5
  2. Building a Sample
  3. Introducing Class Destructors
  4. Testing the Previous User
By: Alejandro Gervasio
Rating: starstarstarstarstar / 13
January 16, 2008

print this article



Building a sample PHP 5 class that doesn’t use a destructor

An adequate point to start demonstrating how to declare and use class destructors is to step on the opposite side of the river (yes, my metaphoric skills really amaze me all the time). By this I mean building a sample class that lacks a destructor method, as you’ve done probably hundreds of times when using classes in PHP 4.

Having said that, suppose that a specific PHP application requires working with objects that represent a determined range of users. Based upon this fictional scenario, I’m going to define a generic class, called “User,” which is convenient for storing some common properties of these hypothetical users, such as their first and last names, and their email addresses as well.

Basically, this class has the following signature:

// define 'User' class

class User{

private $firstName;

private $lastName;

private $email;

public function __construct($firstName,$lastName,$email){


throw new Exception('Invalid First Name parameter!');



throw new Exception('Invalid Last Name parameter!');



throw new Exception('Invalid Email parameter!');






// get user's first name

public function getFirstName(){

return $this->firstName;


// get user's last name

public function getLastName(){

return $this->lastName;


// get user's email

public function getEmail(){

return $this->email;


// get all user data

public function getAll(){

return 'First Name: '.$this->firstName.' Last Name: '.$this->lastName.' Email Address: '.$this->email;



As shown above, the “User” class that I just defined exposes some basic properties, along with a group of accessing methods tasked with returning the values assigned to the properties to client code. So far, understanding how this class works isn’t going to make you lose your hair, right?

After defining that simple “User” class, it’s time to see how it works in a concrete case, so let me show you a basic script that first creates a new user object, then assigns some trivial values to the pertinent properties, and finally outputs these values to the browser.

The signature of the script looks like this:


// create new instance of 'User' class

$user=new User('John','Doe','john@domain.com');

// display separately user data

echo 'First Name: '.$user->getFirstName().'<br />';

echo 'Last Name: '.$user->getLastName().'<br />';

echo 'Email: '.$user->getEmail().'<br />';

// display all user information

echo 'Complete user information: '.$user->getAll();


/* displays the following


First Name: John

Last Name: Doe

Email: john@domain.com

Complete user information: First Name: John Last Name: Doe Email Address: john@domain.com





catch(Exception $e){

echo $e->getMessage();



Until now, the class performs fairly well. As you can see in the previous example, a user object is created and its properties are accessed via the corresponding methods. What else could you ask for? Well, not so fast. Suppose for an instant that you need to serialize the entire object for debugging purposes, right before the script finishes its execution.

This could be quickly done by defining an additional class method that performs this serialization process. However, in doing so, the method should be called explicitly, right? Here’s where class destructors come in, since in PHP 5 it’s possible to implement concretely a “__destruct()” method, which will be automatically called by the interpreter (not direct invocation is needed) before an object is destroyed.

In this particular case, the above user object could simply use a destructor to serialize itself, prior to being removed from the web server’s memory. Sounds quite useful, doesn't it? All right, now that you've seen how to work with a generic user class that doesn’t declare a “__destruct()” method as part of its API, it’s time to learn how to implement a basic destructor within the aforementioned class.

As you might have guessed, I’ll be analyzing destructors in the upcoming section, so go ahead and read it. It’s only one click away.

>>> More PHP Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: