Magic Methods in PHP

In this article I explain PHP magic methods like sleep method and wakeup methods.
  • 1032

Introduction

In this article you will be learn the PHP "magic" methods. The PHP magic methods start with double underscore characters, as in "_" and another "_" (in other words "_ _"), and they are:

  • __construct()
  • __destruct()
  • __call()
  • __sleep()
  • __callstack()
  • __get()
  • __set()
  • __unset()
  • __walkup()
  • __tostring()
  • __invoke()
  • __setstate()
  • __clone()

Why they are called "magic" methods

Its definition is provided by programmers, in other words by you. PHP does not provide the definition of these methods. The programmer writes the code that defines what actually these methods will do. The user cannot call these methods, that is why it is called "magic" methods because PHP will call the functions behind the scene and these methods are always defined within the class. I am providing an example to clarify my point better.

_sleep and _wakeup method in PH
P

_sleep()

It is useful when we have a large object in our program and we do not want to save the object completely. It is also used to commit and perform simple clean up tasks.

_wakeup()

It is useful when we want to reconstruct any resource that the object may have, or say it is used to reestablish the database connections that may have been lost.

Example of __sleep and __wakeup magic methods


<?php

class
userConnection
{

protected
$con;
private
$serverName, $userName,$password,$dbname;
public
function __construct($serverName, $userName,$password,$dbName)
{
$
this->server=$serverName;
$
this->username=$userName;
$
this->password=$password;
$
this->dbanme=$dbName;
$
this->connect();
}

private
function connect()
{
$
this->con=mysql_connect($this->server,$this->username,$this->password);
mysql_select_db($
this->dbanme,$this->con);
if
(!$this->con)
{
die(
'Could not connect: ' . mysql_error());
}
echo
"Connection is Successfully established.";
}

public
function __sleep()
{

return
array($serverName, $userName,$password,$dbName);
}

public
function _wakeup()
{
this->connect();
}
$obj=
new userConnection('localhost','root','','mysql');
?>


Output

magic-methods-in-php.jpg

© 2013 dotNetheaven. All rights reserved.