RSS

Category Archives: Magic Methods

__clone()

In PHP 5 when you assign one object to another object creates a reference copy and does not create duplicate copy. This would create a big mess as all the object will share the same memory defined for the object. To counter this PHP 5 has introduced clone method which creates an duplicate copy of the object. __clone magic method automatically get called whenever you call clone methods in PHP 5.

Without Object Cloning :

<?php
class Animal
{
   public $name;
   public $legs;

   function setName($name)
   {
	$this->name = $name;
   }

   function setLegs($legs)
   {
	$this->legs = $legs;
   }
}

$tiger = new Animal();
$tiger->name = "Tiger";
$tiger->legs = 4;

$kangaroo = $tiger;
$kangaroo->name = "Kangaroo";
$kangaroo->legs = 2;

echo $tiger->name."---".$tiger->legs;
echo "
".$kangaroo->name."---".$kangaroo->legs;
?>

The output will be:

Kangaroo—2
Kangaroo—2

Here i have created an $tiger object of Animal class. Created another variable $kangaroo and assigned $tiger to $kangaroo. After echo it print the details entered last because both the variables are referring to the same memory location

Above example with clone function :

<?php
class Animal
{
   public $name	;
   public $legs;

   function setName($name)
   {
	$this->name = $name;
   }

   function setLegs($legs)
   {
	$this->legs = $legs;
   }

   function __clone()
   {
	echo "
Object Cloning in Progress";
   }
}

$tiger = new Animal();
$tiger->name = "Tiger";
$tiger->legs = 4;

$kangaroo = clone $tiger;
$kangaroo->name = "Kangaroo";
$kangaroo->legs = 2;

echo "
".$tiger->name."---".$tiger->legs;
echo "
".$kangaroo->name."---".$kangaroo->legs;
?>

The output will be :

Object Cloning in Progress
Tiger—4
Kangaroo—2

Here i have created an $tiger object of Animal class. Created another variable $kangaroo having clone of $tiger. This calls the __clone magic method. After echo it print the details entered by individual object as both of them are referring to separate object and memory location.

The above technique of cloning discussed is called shallow copy. There are other techniques called Deep Copy wherein you create duplicate copy of objects referring to other objects etc.

Advertisements
 
Leave a comment

Posted by on June 6, 2011 in Magic Methods, PHP

 

__unset()

The __unset() magic method of PHP5 is called whenever unset function of PHP is called to clear an undeclared data member. With the help of this method we can check for the undeclared variables in the code. We can also set appropriate error message while testing for variable names getting used in the Class.

<?php
class magicmethod
{
	function __unset($variablename)
	{
		echo "Variable '".$variablename."' not Set and Cannot be UnSet";
	}
}
$a = new magicmethod();
unset($a->name);
?>

Here i am trying to destroy the name attribute using isset function of PHP. But the name attribute is not defined inside magicmethod class so the PHP compiler call the __unset() method where an appropriate error message is displayed. Thus the output will be:

Variable ‘name’ not Set and Cannot be UnSet
 
Leave a comment

Posted by on June 6, 2011 in Magic Methods, PHP

 

__isset()

The __isset() magic method in PHP5 is called whenever isset function of PHP is called to check for undeclared data member. With the help of this method we can check for the undeclared variables in the code. We can also set appropriate error message while testing for variable names getting used in the Class.

<?php
class magicmethod
{
	function __isset($variablename)
	{
		echo "Variable '".$variablename."' not Set";
	}
}
$a = new magicmethod();
isset($a->name);
?>

Here i am trying to check whether the name attribute is set or not using isset function of PHP. But the name attribute is not defined inside magicmethod class so the PHP compiler call the __isset() method where an appropriate error message is displayed. Thus the output will be :

Variable ‘name’ not Set
 
Leave a comment

Posted by on June 6, 2011 in Magic Methods, PHP

 

__destruct()

Destructor are special function in Object Oriented Programming. It gets called automatically whenever object of a class is destroyed or goes out of scope. This is useful for clean up operation before cleaning the memory. PHP 5 uses special keyword “__destruct” to definedestructor of the class.

<?php
class employee
{
    function __destruct()
    {
        echo "Destructor Called";
    }
}
$a = new employee();
?>

So when the page operation is completed destructor function is called automatically.

 
Leave a comment

Posted by on June 6, 2011 in Magic Methods, PHP

 

__construct()

Constructor are special function in Object Oriented Programming. It gets called automatically whenever object of a class is created. This is useful for performing any pre operation before we start to call the methods of the class. PHP5 uses special keyword “__construct” to define constructor of the class.

<?php
class employee
{
    function __construct()
   {
       echo "Constructor Called";
   }
}
$a = new employee();
$a = new employee;

Here i initializing the employee class which internally calls its constructor.

<?php
class employee
{
     function __construct()
     {
         echo "Constructor Called";
     }
}
$a = new employee(12);

Now here we are passing a value to the constructor but the constructor definition does not have a argument definition. In OOP language like Java, C++, .Net this will throw an error but in PHP5 this will works as PHP5 implements loosely typed techniques and does not fully support Function OverLoading Technique.

 
Leave a comment

Posted by on June 6, 2011 in Magic Methods, PHP

 

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

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 ofserialize and unserialize functions and another one is use of json_encode and json_decodefunctions. 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 :

<?php
	/**
	 * Case I - Using serialize and unserialize
	 */
	// For generating string representation of data.
	$stringRepresentation = serialize( $myVar );
	// For regenerating the same data again.
	$myVar = unserialize( $stringRepresentation );

	/**
	 * Case II - Using json_encode and json_decode
	 */
	// For generating string representation of data.
	$stringRepresentation = json_encode( $myVar );
	// For regenerating the same data again.
	$myVar = json_decode( $stringRepresentation );

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 :

<?php
	class ConnectDb {
		private $_hostName = 'localhost';
		private $_userName = 'mysqluser';
		private $_password = 'mysqluserpassword';
		private $_selectedDb = 'my_blog_db';

		public function connect() {
			// code for connecting to database
		}

		function __sleep() {
			return array( '_hostName', '_userName', '_selectedDb' ); // Export just these three data members, leaving password
		}
	}

	$connectToDb = new ConnectDb();
	$connectToDb->connect();
	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";}"
 
Leave a comment

Posted by on June 6, 2011 in Magic Methods, PHP

 

__toString()

__toString() allows you to set a string value for the object that will be used if the object is ever used as a string. This is a fairly simple magic function, and works like this:

<?php
    class cat {
        public function __toString() {
            return "This is a cat\n";
        }
    }

    $toby = new cat;
    print $toby;
?>

To make this work in PHP 5 caused quite a lot of headaches for the PHP developers – getting the balance right as to when objects should be converted and when they should not took a lot of debating.

 
Leave a comment

Posted by on June 6, 2011 in Magic Methods, PHP