PHP Magic Functions – Best Part of Object Oriented PHP – Part 1

On 04.28.11, In Dexter at Lab, PHP

There are some reserved function names  in PHP class starting with __ ( double underscore ). These are __construct, __destruct, __isset, __unset, __call, __callStatic, __sleep, __wakeup, __get, __set, __toString, __set_state, __invoke and __clone. You cannot use these functions to serve your logical purpose but these are meant to be used for providing magic functionality.

Lets start with the most familiar ones …

__construct and __descruct : Play with birth ( initialization ) and death ( destroy ) of an object

These methods are better known as constructor ( called when object is initialized ) and destructor ( called when object is destroyed or scope of an object vanishes ), well known keywords in Object Oriented Programming. Most of you guys are already familiar with these functions therefore I am not going to discuss them in detail.

__call and __callStatic : Don’t leave any undefined function in your class

There are two ways of calling a class function. First one is with Object Scope and second one is with Static Scope. In former case an object of the class is first instantiated and then a function is called using the -> ( I’m missing its name, any suggestion !!! ) operator while in latter case the function is called using the Scope Resolution Operator( :: ) with class name.

Whenever you try to access a function of your class with object scope which is not defined it throws an error. e. g.

1
2
3
4
5
6
7
Scroll to Top