HomePHP The Sleep and Wakeup Magic Functions in PHP 5
The Sleep and Wakeup Magic Functions in PHP 5
Magic functions are an important part of the numerous improvements and additions that were introduced originally in PHP 5. They can be extremely handy when it comes to simplifying the execution of complex tasks. This is the fourth part of a seven-part series that showcases some of the more useful magic functions and how to implement them.
Ranging from overloading properties and methods of a class, including automatically overloading classes and triggering specific processes before destroying objects, magic functions can be used for doing all sorts of clever things. Some of these have been rather overlooked by many developers, quite possibly because they're not aware of their full potential.
However, if you've been a patient follower of this series of articles and have read all of the preceding tutorials, then you're familiar with using some of the most relevant magic functions in concrete cases, including the "__set()," "__get()" and "__call()" trio, and the "__isset()" and "__ unset()" functions as well.
In the last tutorial I explained how to overload a method of a basic class via the aforementioned "__call()" function, which, as you'll surely recall, is invoked behind the scenes by the PHP engine each time it finds a reference to a non-existent method of a class.
Indeed, method overloading is a powerful approach that allows you to perform complicated tasks with a minimal amount of code, even when this benefit comes at the expense of making the code harder to read and maintain in many cases.
The purpose of this series of article is to explore the most relevant PHP 5 magic functions, so it's time to talk about the ones that I plan to discuss in the next few lines. So, as this article's title suggests, in this fourth chapter I'm going to examine closely the "__sleep()" and "__wakeup()" functions, which are called automatically when an object is serialized and unserialized respectively.
By the end of this article, you'll be armed with the right pointers to start using these functions inside your own PHP applications, so let's get started.