PHP Magic Functions: Best Part of Object Oriented PHP – Final Part


Continuing my posts on PHP Magic Functions lets close this topic now and talk about rest of the Magic Functions.

__sleep and __wakeup : Serialize and Unserialize Your Objects as You Wish

Before talking about these magic functions, I want you to be clear about serialization and unserialization of a variable. Some times you need to ( may be you’ve never done so but now you’ll atleast think about it ) store ( using string representation ) your variable to database or primary storage or session or any where and from that location you can get the same value again.

To acheive this you can use either of two available possiblilities in PHP. First one is use of serialize and unserialize functions and another one is use of json_encode and json_decode functions. I personally prefer the formar approach since serialize and unserialize functions are quite faster than json_encode and json_decode functions. The latter approach is useful when you need to port your data from php to other programming languages like javascript or actionscript etc.

Have take a look, what I’m talking about …

If you call serialize function on an object then it checks first whether there you've written __sleep magic function or not in your class. If you've then that function gets executed and the return value of the function is serialized or the object itself gets serialized. Now think where it can be useful. Suppose you've a class that connects you to the mysql database and stores basic information required for that ( host, user name, password ) then you'll never wish to serialize your object along with your secret informations ( password in this case ). In that case you can employee the __sleep magic function and choose which values you want to export from the object. Lets see how I'll code my database connect class ...

	var_dump( serialize( $connectToDb ) );

The above snippet of code will output something like this ...

string(156) "O:9:"ConnectDb":3:{s:20:"ConnectDb_hostName";s:9:"localhost";s:20:"ConnectDb_userName";s:9:"mysqluser";s:22:"ConnectDb_selectedDb";s:10:"my_blog_db";}"
  • May 16, 2011
8 Best Free Stock Video Websites for Tiktok, Reels, and Shorts Top 5 PHP Frameworks: Fast and Secure