Friday, March 27, 2015

Send a notification on iPhone

First of all we need 3 things as mentioned:

1. Our iPhone's device token
2. .pem file for iPhone
3. Its passphrase.

Now use following code:

        $deviceToken = 'enter_your_device_token';
        $passphrase = 'enter_your_passphrase';
        $message = 'enter_your_notification_message';

        $badge = 1;
        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', 'path_to_pem_file.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

        // Open a connection to the APNS server
        $fp = stream_socket_client(
            'ssl://gateway.sandbox.push.apple.com:2195', $err,
            $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
        if (!$fp)
            exit("Failed to connect: $err $errstr" . PHP_EOL);
        echo 'Connected to APNS' . PHP_EOL;

        // Create the payload body
        $body['aps'] = array(
            'alert' => $message,
            'badge' => $badge,
            'sound' => 'newMessage.wav'
        );

        // Encode the payload as JSON
        $payload = json_encode($body);

        // Build the binary notification
        $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

        // Send it to the server
        $result = fwrite($fp, $msg, strlen($msg));

        if (!$result)
            echo 'Error, notification not sent' . PHP_EOL;
        else
            echo 'notification sent!' . PHP_EOL;

        // Close the connection to the server
        fclose($fp);


Thanks.

Friday, March 20, 2015

11 Rules All Programmers Should Live By

1: Technology is how you get to the solution, it is not THE solution
We can get really carried away with the latest JavaScript framework—ahem, Angular—IoC container, programming language or even operating system, but all of these things are not actually solutions to the problems we are trying to solve as programmers, instead they are simply tools that help us solve the problems.
We have to be very careful not to get too crazy about a particular technology that we happen to like or that happens to be oh so popular right now, lest we run the risk of thinking about every problem as a nail, just because we happen to be holding a shiny hammer we just learned about.

2: Clever is the enemy of clear

When writing code, we should strive to write code that is clear and easy to understand.
Code that clearly communicates its purpose is much more valuable than code that is obscure—no matter how clever it may be.
It’s not always true, but in general, clever is the enemy of clear.
It’s usually true that when we write code that is “clever,” that code isn’t particularly clear.
It’s important to remember this rule whenever we think we are doing something particularly clever.
Sometimes we write clever code that is also clear, but usually that is not the case.
If you’re interested in writing clean code I highly recommend you check out The Clean Coder: A Code of Conduct for Professional Programmers (Robert C. Martin)
code

3: Only write code if you absolutely have to

This one might seem a little contradictory, after all, isn’t our job as programmers to write code?
Well, yes and no.
Our jobs may involve writing code, but we should still strive to write as little of it as possible to solve the problem we are trying to solve.
This doesn’t mean we should make our code as compact as possible and name all our variables using single letters of the alphabet. What it does mean is that we should try to only write code that is actually necessary to implement the functionality that is required.
Often it is tempting to add all kinds of cool features to our code or to make our code “robust” and “flexible” so that it can handle all different kinds of situations. But, more often than not, when we try to guess about what features would be useful or we try to pave the road to solve for problems that we think might exist in the future, we are wrong.
This extra code may not add any value, but it can still do a lot of harm. The more code there is, the more chances for bugs and the more code that has to be maintained over time.
Good software engineers don’t write code unless it’s absolutely necessary.
Great software engineers delete as much code as possible.

4: Comments are mostly evil

“Every time you write a comment, you should grimace and feel the failure of your ability of expression.”
This doesn’t mean that you should never write comments, but for the most part they can be avoided and instead we can focus on doing a better job of naming things.
Comments should only really be written when it’s not possible to clearly communicate the intent of a variable or method by using a name. The comment then serves an actual purpose that could not be easily expressed in the code.
For example, a comment could tell us that this strange order in which some operation was occurring in the code was not a mistake, but was intentional because of a bug in the underlying operating system.
In general though, comments are not only evil because in many cases they are necessary, but also because they lie.
Comments don’t tend to get updated with the rest of the code and this results in the comments actually becoming dangerous, because they very well could steer you in a completely wrong direction.
Do we check every single comment against the code to make sure the code is actually doing what the comment says? If so, what is the point of having the comment? If not, how can we trust that the comment is telling us the truth?
It’s a pickle, so it’s best to avoid it as much as possible.
5: Always know what our code is supposed to do before we start writing it
It seems obvious, but it isn’t.
How many times have we sat down to write code without fully understanding what the code we were writing was actually supposed to do?
I’ve done it more times than I’d like to admit, so this is a rule that I need to read often.
Practicing test driven development (TDD) can help here, because we literally have to know what the code is going to do before we write it, but it still doesn’t stop us from creating the wrong thing, so it’s still important to make sure we absolutely, 100% understand the requirements of the feature or functionality we are building before we build it.

6: Test our sh—code before we ship it

Don’t just toss our code over the wall and have QA pound on it only to send it back to us so that we can waste a bunch of everyone’s time with unnecessary bug reports and resolutions.
Instead, take a few minutes to run through the test scenarios ourself, before we call our code done.
Sure, we won’t catch every bug before we pass our work on to QA, but we’ll at least catch some of the stupid and embarrassing mistakes that we all make from time-to-time.
Too many software developers think that it is only QA’s job to test their stuff. It’s simply not true. Quality is everyone’s responsibility.
wStack of open books

 7: Learn something new every day

If we didn’t learn something new today, we just made backwards progress, because I can guarantee you forgot something.
It doesn’t take a lot of time to learn something new each and every day.
The little advances  we make each and every day add up over time and will greatly shape our future. But, we have to start investing now if we want to reap the rewards later.
Besides, today technology is changing so rapidly that if we aren’t continually improving our skills and learning new ones, we are going to be left behind very quickly.

8: Writing code is fun

That’s right. We probably didn’t get into this profession just because it pays well.
I mean, there is nothing wrong with picking a job that pays well, but doctor or lawyer would have probably been a better choice.
Most likely we became a software developer, because we love wirting code. So, we don’t forget that we are doing what we love.
9: We can’t know it all
As much as you learn, there is still going to be a lot you don’t know.
It’s important to realize this because we can drive yourself nuts trying to know everything.
It’s OK to not have all the answers.
It’s OK to ask for help or to speak up when we don’t understand something.
In many cases, we can learn what we need to know pretty darn close to when you need to know it—believe me, I do it all the time.
My point is, don’t get caught up in trying to learn it all, when that is an impossible task. Instead, focus on learning what you need to know and building the skills that enable you to learn things quickly.

10: Best practices are context dependent

Is test-driven development, the best way to write code?
Should we always pair program?
Are we a scrub if we don’t use IoC containers?
The answer to all of these questions is “it depends.”
It depends on the context.
People will try to shove best practices down our throat and they’ll try to tell us that they always apply—that we should always do this or that—but, it’s simply not true.
I follow a lot of best practices when I am writing code, but I also conditionally don’t follow them as well.

11: Always strive to simplify

All problems can be broken down.
The most elegant solutions are often the most simple ones.
But, simplicity doesn’t come easy. It takes work to make things simple.
The purpose of this blog is to take some of the complexities of software development, and life in general, and make them simple.
Believe me, this isn’t an easy task.
Any fool can create a complex solution to a problem. It takes extra effort and care to refine a solution to make it simple, but still correct.
Take the time. Put forth the effort. Strive for simplicity.

Modifying an HTTP Response

Because the PHP engine interacts with the Web server, our PHP scripts can influence the HTTP response headers sent by the server. This can be very useful.
To get the Web server to send a custom HTTP header as part of its response, we will use the PHP's header() function. This simply takes the header line to output, and then injects this line into the response headers:

header( "Server: Never you mind" );

By default, the header() function replaces any HTTP header field with the same name. In the example just shown, if the response already contains a Server header, that header is replaced with the one passed into the header() function. However, some HTTP header fields can be included more than once in the response. If we'd like to include the same header several times, pass in false as the second argument to the header() function:

  1. header( "Set-Cookie: name=Fred; expires=Mon, 05-Jan-2009 10:22:21 GMT; path=/; domain=.example.com");
  2. header( "Set-Cookie: age=33; expires=Mon, 05-Jan-2009 10:22:21 GMT; path=/; domain=.example.com", false );

(Although we can set cookies this way, it's easier to use PHP's setcookie() function.)

Generally speaking, when we pass a header line to the header() function, PHP faithfully injects the header line as-is into the response. However, there are two special cases:
  • If the header string starts with HTTP/, PHP assumes we want to set the status line, rather than add or replace a header line. This allows us to set our own HTTP status lines:

    // Nothing to see here, move along
     header( "HTTP/1.1 404 Not Found" );
  • If we pass in a Location header string, PHP automatically sends a 302 Found status line as well as the Location header:

    // Redirect to the login page
     header( "Location: http://www.example.com/login.php" );
  • This makes it easy to do page redirects . If we'd rather send a different status line, simply specify the status line as well:

    header( "HTTP/1.1 301 Moved Permanently" );
    header( "Location: http://www.example.com/newpage.php" );
The header() function is very useful if our PHP script needs to send anything other than an HTML Web page. For example, say we have a report.pdf file on the Web server, and we want to send this to the browser. We could write the following:

  1. <?php
  2. header( "Content-Type: application/pdf" );
  3. readfile( "report.pdf" );
  4. ?>

The first line tells the Web browser to expect a PDF document rather than a regular Web page. The second line reads the PDF file on the server's hard drive and outputs its contents to the Web browser, which can then save or display the PDF.

Usually it's up to the browser as to whether it displays the file in the browser itself, or offers to save it to the user's hard disk. We can use a Content-Disposition: Attachment header to suggest to the browser that the file should be saved rather than displayed and, optionally, to suggest a filename for the saved file:

  1. <?php
  2. header( "Content-Type: application/pdf" );
  3. header( 'Content-Disposition: attachment; filename="Latest Report.pdf"' );
  4. readfile( "report.pdf" );
  5. ?>

By the way, we need to make sure we don't send anything to the browser before calling header(). This includes HTML markup, or even blank lines, before your opening <?php tag. This is because, once PHP has received a request to send some content to the browser, it sends the HTTP headers first (because the headers need to be sent at the start of the response). Therefore, by the time our header() call is executed, the content is already being sent, and it's too late to send any more headers. (If we fall foul of this, then our header isn't sent and PHP generates a Cannot modify header information - headers already sent warning.)

Friday, March 13, 2015

Using Exception Objects to Handle Errors

Using Exception Objects to Handle Errors

Although functions like trigger_error() and set_error_handler() give us a lot of flexibility with raising and handling errors, they do have limitations. For example, if a piece of code calls a class method and an error occurs in that method, it would be nice if the method could simply tell the calling code about the error, rather than having to raise an error with trigger_error() and go through a central error handler. That way the calling code could take action to correct the problem, making the application more robust.

One simple, common way to achieve this is to get a function or method to return a special error value, such as -1 or false. The calling code can then inspect the return value and, if it equals the error value, it knows there was a problem. However, this can get unwieldy when you start working with deeply nested function or method calls, as the following code shows:

class WarpDrive {
   public function setWarpFactor( $factor ) {
     if ( $factor >=1 && $factor <= 9 ) {
       echo "Warp factor $factor<br />";
       return true;
     } else {
       return false;
     }
   }
 }
 class ChiefEngineer {
   public function doWarp( $factor ) {
     $wd = new WarpDrive;
     return $wd->setWarpFactor( $factor );
   }
 }
 class Captain {
   public function newWarpOrder( $factor ) {
     $ce = new ChiefEngineer;
     return $ce->doWarp( $factor );
   }
 }
 $c = new Captain;
 if ( !$c->newWarpOrder( 10 ) ) echo "She cannot go any faster!<br />";

The WarpDrive::setWarpFactor() function returns true if the function succeeded, and false otherwise (if the warp factor was less than 1 or greater than 9). This return value then needs to be passed through both the ChiefEngineer::doWarp() method and the Captain::newWarpOrder() method to reach the calling code, which can then identify and report on the error. It's not uncommon to find at least this level of nested method calls in complex applications.

Another problem is that simply returning false doesn't tell the calling code much about what went wrong. What's more, when a method has to return an error value, it can't then easily return anything else (because methods and functions can return only one thing at a time).

Fortunately, PHP gives us exceptions, which are a much more elegant way of triggering and handling error conditions. Rather than returning a single error value, our method or function can create a rich Exception object that includes detailed information about the problem, then throw the object up to the calling code to handle, or catch.

Another nice feature of exceptions is that the calling code doesn't have to catch an exception if it doesn't want to; if it ignores it, the exception is re-thrown up the calling chain until it is caught. If no code catches the exception, the script halts with a fatal error and the exception is logged or displayed to the user (depending on our log_errors and display_errors settings). So by using exceptions, any problem can either be handled automatically by another part of the application or, if all else fails, reported to the developer or user. This allows applications to be much more flexible and robust in their handling of error scenarios.

Note: If we don't want uncaught exceptions to raise fatal errors, we can create our own exception handler to deal with the exceptions (much like creating our own error handler).
See http://www.php.net/manual/en/function.set-exception-handler.php for details.

Throwing Exceptions

Here's how to create and throw an exception when an error occurs in our code:

throw new Exception;

We can also pass an optional error message to the Exception object when it's created (this is generally a good idea):

throw new Exception( "Oops, something went wrong" );

If we have a lot of different error messages in our application, it can help to give each exception a numeric error code to distinguish it. To add an error code to our thrown exception, pass it as the second argument when creating the Exception object:

If we don't catch our thrown exception at some other point in our code, eventually it bubbles up to the top level of our script, displaying an error message similar to the following:

PHP Fatal error:  Uncaught exception 'Exception' with message 'Oops, something went wrong' in script.php:4
 Stack trace:
 #0 {main}
   thrown in script.php on line 4

This tells us that an exception occurred that wasn't handled by the script itself, gives us the error message, and informs us that the exception was thrown in the main (top-level) part of the script.

Friday, February 27, 2015

Storing Objects as Strings

Objects that we create in PHP are stored as binary data in memory. Although we can pass objects around using PHP variables, functions, and methods, sometimes its useful to be able to pass objects to other applications, or via fields in Web forms, for example.

PHP provides two functions to help us with this:

    serialize() converts an object — properties, methods, and all — into a string of text
    unserialize() takes a string created by serialize() and turns it back into a usable object

The following example shows these two functions in action:

 class Person
 {
   public $age;
 }
 
 $harry = new Person();
 $harry->age = 28;
 $harryString = serialize( $harry );
 echo "Harry is now serialized in the following string: '$harryString'<br />";
 echo "Converting '$harryString' back to an object...<br />";
 $obj = unserialize( $harryString );
 echo "Harry's age is: $obj->age<br />";


This code creates a simple Person class with one property, $age. It then creates a new Person object, $harry, and sets its $age property to 28. It calls serialize() to convert the object to a string, which it displays. Finally, it converts the string back into a new object, $obj, then displays its $obj->age property (28). Here's the result of running the script:

 Harry is now serialized in the following string: 'O:6:"Person":1:{s:3:"age";i:28;}'
 Converting 'O:6:"Person":1:{s:3:"age";i:28;}' back to an object...Harry's age is: 28

We can actually use serialize() and unserialize() on any PHP value, not just objects. However, it's especially useful with objects and arrays, because these structures can be quite complex and it's not easy to convert them to strings in any other way.

What's more, when we serialize an object, PHP attempts to call a method with the name __sleep() inside the object. We can use this method to do anything that's required before the object is serialized. Similarly, We can create a __wakeup() method that is called when the object is unserialized.

__sleep() is useful for cleaning up an object prior to serializing it, in the same way that we might clean up in a destructor method. For example, we might need to close database handles, files, and so on. In addition, __sleep() has another trick up its sleeve. PHP expects our __sleep() method to return an array of names of properties to preserve in the serialized string. We can use this fact to limit the number of properties stored in the string — very useful if our object contains a lot of properties that we don't need to store.

Here's an example:

class User {
   public $username;
   public $password;
   public $loginsToday;
 
   public function __sleep() {
     // (Clean up; close database handles, etc)
     return array( "username", "password" );
   }
 }
 
 $user = new User;
 $user->username = "harry";
 $user->password = "monkey";
 $user->loginsToday = 3;
 echo "The original user object:<br />";
 print_r( $user );
 echo "<br /><br />";
 echo "Serializing the object...<br /><br />";
 $userString = serialize( $user );
 echo "The user is now serialized in the following string:<br />";
 echo "$userString<br /><br />";
 echo "Converting the string back to an object...<br /><br />";
 $obj = unserialize( $userString );
 echo "The unserialized object:<br />";
 print_r( $obj );
 echo "<br />";


This code outputs the following:

 The original user object:
 User Object ( [username] => harry [password] => monkey [loginsToday] => 3 )
 
 Serializing the object...
 
 The user is now serialized in the following string:
 O:4:"User":2:{s:8:"username";s:5:"harry";s:8:"password";s:6:"monkey";}
 
 Converting the string back to an object...
 
 The unserialized object:
 User Object ( [username] => harry [password] => monkey [loginsToday] => )


In this example, we don't care about preserving the number of times the user has logged in today, so the __sleep() method only returns the "username" and "password" property names. Notice that the serialized string doesn't contain the $loginsToday property. Furthermore, when the object is restored from the string, the $loginsToday property is empty.

In a real-world situation, We make sure that we don't transmit sensitive information such as usernames as passwords as plain text strings if there's a chance that the data might be intercepted or read by untrusted third parties.

If we do need to preserve all our object's properties, we can use the built-in get_object_vars() function to get an associative array of all the properties in the object, then we use the array_keys() function to get just the property names as an array, which we can then return from our __sleep() method:

class User {
   public $username;
   public $password;
   public $loginsToday;
 
   public function __sleep() {
     // (Clean up; close database handles, etc)

     return array_keys( get_object_vars( $this ) );

   }
 }


Finally, here's an example that shows the __wakeup() method in action:

 class User
 {
   public function __wakeup()
 {
     echo "Yawn... what's for breakfast?<br />";
   }
 }
 
 $user = new User;
 $userString = serialize( $user );
 $obj = unserialize( $userString );  // Displays "Yawn... what's for breakfast?"

Friday, February 20, 2015

PHP : Automatically Loading Class Files

Generally it's a good idea to keep our classes in separate script files, one class per file. It also helps to name each class file after the class it contains. For example, we might create a class called Person and store it in a file called Person.php inside a classes folder (so that we know that Person.php contains a class). Or if we have created a class called Fruit, we might store it in a file called class.Fruit.php.

Then, when our script needs to create a Person object, it can include the Person.php file to create the class, then go ahead and create an object from the class:

 <?php
 require_once( "classes/Person.php" );
 $p = new Person();
 ?>

require_once() lets us include one PHP script file inside another, which means we can break up our PHP application into small, manageable script files. Not only does this good practice help to keep our scripts organized and maintainable, but it lets us take advantage of a nifty feature of PHP: class autoloading.

With autoloading, we create an __autoload() function somewhere in our script. This function should accept a class name as an argument. Then, whenever another part of our script attempts to create a new object from a nonexistent class, __autoload() is automatically called, passing in the class name. This gives our __autoload() function a chance to find and include the class file, thereby allowing the PHP engine to carry on and create the object.

Here's an example __autoload() function:

function __autoload( $className ) {
   $className = str_replace ( "..", "", $className );
   require_once( "classes/$className.php" );
 }

This function stores the name of the nonexistent class in a $className parameter. It then filters this parameter to ensure it contains no ".." substrings (which could potentially be used by an attacker to open files or folders above the classes folder). Finally, it calls PHP's require_once() function to load the file in the classes folder with the same name as the missing class. This should cause the class to be created, allowing the object in turn to be created from the class.

For example, imagine the same script contained the following code:

$p = new Person;

When the PHP engine encounters the new Person construct, it looks to see if the Person class has been defined. If not, it calls the previously defined __autoload() function. This in turn includes and runs the file Person.php inside the classes folder, which creates the class and allows the new Person object to be created.

If the PHP engine can't find an __autoload() function, or if our __autoload() function fails to load the Person class, the script exits with a "Class 'Person' not found" error.

spl_autoload_register()

The major drawback to the __autoload() function is that we can only provide one autoloader with it. PHP 5.1.2 introduced spl_autoload() which allows us to register multiple autoloader functions, and in the future the __autoload() function will be deprecated.

The introduction of spl_autoload_register() gave us (programmers) the ability to create an autoload chain, a series of functions that can be called to try and load a class or interface. For example:

<?php
function autoloadRegister($className) {
    $filename = "class/register/" . $className . ".php";
    if (is_readable($filename)) {
        require $filename;
    }
}

function autoloadPerson($className) {
    $filename = "class/person/" . $className . ".php";
    if (is_readable($filename)) {
        require $filename;
    }
}

spl_autoload_register("autoloadRegister");
spl_autoload_register("autoloadPerson");

Generally the functions are called in the order they’re registered, but the order can also be affected by additional arguments passed to spl_autoload_register(). It’s important to remember that once a function has been registered with spl_autoload_register(), the __autoload() function will no longer be called. If we have an __autoload() function we want to run as part of our autoloader chain, then we’ll have to register it with spl_autoload_register().

Friday, February 13, 2015

Php's Constructors and Destructors

Constructors and Destructors

When creating a new object, often it's useful to set up certain aspects of the object at the same time. For example, we might want to set some properties to initial values, fetch some information from a database to populate the object, or register the object in some way.

Similarly, when it's time for an object to disappear, it can be useful to tidy up aspects of the object, such as closing any related open files and database connections, or unsetting other related objects.

Like most OOP languages, PHP provides us with two special methods to help with these tasks. An object's constructor method is called just after the object is created, and its destructor method is called just before the object is freed from memory.

In the following sections we learn how to create and use constructors and destructors.

Setting Up New Objects with Constructors

Normally, when we create a new object based on a class, all that happens is that the object is brought into existence. (Usually we then assign the object to a variable or pass it to a function.) By creating a constructor method in our class, however, we can cause other actions to be triggered when the object is created.

To create a constructor, simply we add a method with the special name __construct() to our class. (That's two underscores, followed by the word "construct," followed by parentheses.) PHP looks for this special method name when the object is created; if it finds it, it calls the method.

Here's a simple example:

 class MyClass
 {
   function __construct()
 {
     echo "Whoa! I've come into being.<br />";
   }
 }
 
 $obj = new MyClass;  // Displays "Whoa! I've come into being."


The class, MyClass, contains a very simple constructor that just displays the message. When the code then creates an object from that class, the constructor is called and the message is displayed.

We can also pass arguments to constructors, just like normal methods. This is great for setting certain properties to initial values at the time the object is created. The following example shows this principle in action:

 class Person
 {
   private $_firstName;
   private $_lastName;
   private $_age;
 
   public function __construct( $firstName, $lastName, $age )
 {
     $this->_firstName = $firstName;
     $this->_lastName = $lastName;
     $this->_age = $age;
   }
 
   public function showDetails()
 {
     echo "$this->_firstName $this->_lastName, age $this->_age<br />";
   }
 }
 
 $p = new Person( "Harry", "Walters", 28 );
 $p->showDetails();  // Displays "Harry Walters, age 28"


The Person class contains three private properties and a constructor that accepts three values, setting the three properties to those values. It also contains a showDetails() method that displays the property values. The code creates a new Person object, passing in the initial values for the three properties. These arguments get passed directly to the __construct() method, which then sets the property values accordingly. The last line then displays the property values by calling the showDetails() method.

If a class contains a constructor, it is only called if objects are created specifically from that class; if an object is created from a child class, only the child class's constructor is called. However, if necessary we can make a child class call its parent's constructor with parent::__construct().

Cleaning Up Objects with Destructors

Destructors are useful for tidying up an object before it's removed from memory. For example, if an object has a few files open, or contains data that should be written to a database, it's a good idea to close the files or write the data before the object disappears.

We create destructor methods in the same way as constructors, except that we use __destruct() rather than __construct():

  function __destruct()
 {
     // (Clean up here)
 }


Note that, unlike a constructor, a destructor can't accept arguments.

An object's destructor is called just before the object is deleted. This can happen because all references to it have disappeared (such as when the last variable containing the object is unset or goes out of scope), or when the script exits, either naturally or because of an error of some sort. In each case, the object gets a chance to clean itself up via its destructor before it vanishes.

Here's an example that shows this concept:

class Person
 {
   public function save()
 {
     echo "Saving this object to the database...<br />";
  }
 
   public function __destruct()
 {
     $this->save();
   }
 }
 
 $p = new Person;
 unset( $p );
 $p2 = new Person;
 die( "Something's gone horribly wrong!<br />");


This code displays the following output:

 Saving this object to the database...
 Something's gone horribly wrong!
 Saving this object to the database...


This Person class contains a destructor that calls the object's save() method to save the object's contents to a database before the object is destroyed. (In this example, nothing is actually saved; instead the message "Saving this object to the database..." is displayed.)

A new Person object is created and stored in the variable $p. Next, $p is removed from memory using the built-in unset() function. Doing this removes the only reference to the Person object, so it's deleted. But just before it's removed, its __destruct() method is called, displaying the message "Saving this object to the database...".

Next the code creates another Person object, storing it in the variable $p2. Finally, the code raises an error using the built-in die() function, which causes the script to end with a "Something's gone horribly wrong!" message. Just before the script finally terminates, however, the object's destructor is called, displaying the "Saving this object to the database..." message.

As with constructors, a destructor of a parent class is not called when the child object is deleted, but we can explicitly call a parent's destructor with parent::__destruct().