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()

__construct is called when an object of a class is created. It is the first method which is called when object is created.

__destruct is called when object of a class is destroyed.

Take an example

__get()

__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

When you execute this code it print Unavailable Age

__set()

__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.

__call()

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

__toString()

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

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.