DoCode: magic functions in PHP

DoCode: magic functions in PHP

 Vaibhav

View (1089)

Magic function are pretty awesome and they allow you to do some amazing and powerful things. The definition of magic function is not provided by the PHP. You as programmer need to provide the definition of the magic function.

The programmer needs to write the code to define what they want  magic function  to do.. however, actually php call the function behind the scene. Since they are not called directly, that is the reason they are called “magic function”.  Lets take an example to make it clear.

How to use magic function

In php, functions that start with “__”  (double underscore) are called magic functions.

Magic function available in PHP are __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload().

Example:

In PHP version 5, the __construct method is basically the constructor for your class

Now, here is an example of a class with the __construct() magic function:


class Automobile {

public $color;      // color of automobile
public $model;     // model number of automobile

public function __construct($color, $model) 
{
 $this->color = $color;  //set the color instance variable
 $this->model = $model; //set the model instance variable

}

}


In this example, we have defined a simple __construct function that just sets the color and model number of Automobile object. Let’s create an object of Automobile class with this code.
 


Automobile auto = new Automobile(red, 100);


Now, if we run this code, a call to __construct function is made as it is the constructor in PHP 5; and the auto object will be an object of Automobile class with color red and model number 100. So, the __construct function is called behind the scene. Isn’t that awesome?

 

About the author

Most Read

The new kid in the block: Android Noughat

Google has been following a similar pattern with its Android naming process....

Watch Security Cams in the open using Google dorks

Are you aware that there is no such thing on the internet as, “Hiding in...

How to create Splash Screen in Android

Android splash screen are normally used to show user some kind of progress...

Reasons that prove BIG DATA is the next Big thing!

According to analysts, the big data market has been predicted to be USD $50...

PHP vs ASP.Net (Championship)

Here we are about to start with the boxing match between two champions.One side...
X
Register Here
 
By signing up , you agree to our Terms of Service and Privacy Policy.
 Login With
Facebook
Facebook
Google
Google
X
Log In Here
 
Remember me Forgot password?
 Login With
Facebook
Facebook
Google
Google
X
Reset Password
 
X

Confirmation Message

Yes No
X
Forgot Password
 
Do you want to Login ?