Magic Methods in PHP

Magic method are specialized method that is executed in response to a specific PHP event.Each magic method is prepended with two underscores. It triggers custom behaviour and defined by programmer inside the class. Some of the magic methods are __construct(),__destruct(), __toString(), __get(), __set(), __call() etc.

New Features in PHP 5.4

PHP Online Video Tutorials

__construct and __destruct Magic Methods

__construct is called when an object of a class is created.

__destruct is called when object of a class is destroyed.

Take an example

class magic
{
function __construct(){
echo "Object is created";
}
function __destruct(){
echo "object is destroyed";
}
}
$magicObject = new magic(); // __construct() is called
unset($magicObject); // __destruct is called

__get Magic Method

__get() is called when the object of a class try to read a property or variable that is inaccessible or unavailable.

**inaccessible means either the property is not defined or it is not public

class student{
public $Name;
public $Address;
public function __get($var){
echo "Unavailable $var";
}
}
$stu = new student;
echo $stu->$Age; // $Age is not available so __get() is called

When you execute this code it print Unavailable Age

__set Magic Method

__set() is called when code tries to set a method that is not accessible.

** If __set() is used to set property that doesn’t exit, the new property will be public.

class student{
public Age;
public function __set($name,$val){
$this->$name = $val;
}   
public function display(){
echo $this->Age;
}
}
$stu = new student;
$stu->Age = 5;
$stu->display();

__call Magic Method

It is called when method of class called does not exist or inaccessible.

class checkcall{
public function __call($method,$argument){
echo "method is not defined";
}
}
$object = new checkcall;
$object->display();   // Display is not defined. so __call is called

__toString() Magic Method

It allows you to set a string value for the object that will be used if the object is ever used as a string

class testString
{
function __toString(){
echo "to string";
}
}
$test = new testString();
echo $test; // You can't echo object. But in this case __toString() is called.

Cons of Magic Method

1. Magic methods are slow.

2. Magic method is public so it ignores scope.

Magic Method Manual

Kumar Singh

About Kumar Singh

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , . Bookmark the permalink.

Comments are closed.