PHP Classes and Objects Defining Object Destructors - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Classes and Objects Defining Object Destructors - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, May 24, 2019

PHP Classes and Objects Defining Object Destructors

PHP Classes and Objects




Defining Object Destructors

Problem

You want to define a method that is called when an object is destroyed. For example, you want to automatically save information from a database into an object when it’s deleted.

Solution

Objects are automatically destroyed when a script terminates. To force the destruction of an object, use unset():

           $car = new car; // buy new car
           // ...
           unset($car); // car wreck

To make PHP call a method when an object is eliminated, define a method named __destruct():

           class car {
                  function __destruct() {
                       // head to car dealer
                  }
           }

Discussion

It’s not normally necessary to manually clean up objects, but if you have a large loop, unset() can help keep memory usage from spiraling out of control.

PHP supports object destructors. Destructors are like constructors, except that they’re called when the object is deleted. Even if you don’t delete the object yourself using unset(), PHP still calls the destructor when it determines that the object is no longer used. This may be when the script ends, but it can be much earlier.

You use a destructor to clean up after an object. For instance, the Database destructor would disconnect from the database and free up the connection. Unlike constructors,you cannot pass information to a destructor, because you’re never sure when it’s going to be run.

Therefore, if your destructor needs any instance-specific information, store it as a property:

           // Destructor
           class Database {
                  function __destruct() {
                       db_close($this->handle); // close the database connection
                  }
           }

Destructors are executed before PHP terminates the request and finishes sending data. Therefore, you can print from them, write to a database, or even ping a remote server.

You cannot, however, assume that PHP will destroy objects in any particular order. Therefore, you should not reference another object in your destructor, because PHP may have already destroyed it. Doing so will not cause a crash, but it will cause your code to behave in an unpredictable (and buggy) manner.


No comments:

Post a Comment

Post Top Ad