In this post, I’ll give you a cheetsheet quick reference to all the magic methods available in PHP.
Whether you are a seasoned PHP developer or a novice in PHP development, if you’ve worked with OOP in PHP, then you’re using at least a couple of PHP magic methods already. However, if you have not heard of PHP magic methods yet, let me introduce them:
The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. All magic methods MUST be declared as public.
If you’re wondering why these methods are called magic methods, it’s because of the fact that if you define one of these methods in your class, it’ll be called automatically and you are just supposed to define what should happen within it. The best example of the magic method is the __construct()
function which is called automatically when the object is instantiated.
In general, magic methods in PHP allow you to perform various kinds of operations with objects. It also allows you to handle certain kinds of situations by manipulating objects.
PHP Magic Methods
The aim of this article is to go through all the magic methods in PHP and explain them each briefly.
The __contruct()
Method
If you define this method in your class, it’ll be called automatically when an object is instantiated. The purpose of this method is to assign some default values to object properties. This method is also called a constructor.
Let’s have a look at a quick example to understand how it works:
<?php class Student { private $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } } $objStudent = new Student('John', '[email protected]'); ?>
In the above example, when you instantiate a new object by with new student('John','
[email protected]
')
, it calls the __construct()
method in the first place. In the __construct()
method, we’ve assigned values passed in the arguments to the object properties.
The __destruct()
Method
The __destruct()
method is called a destructor and it’s called when the object is destroyed. Generally, it’s also called when the script is stopped or exited. The purpose of this method is to provide an opportunity to save the object state or any other cleanups you would want to perform.
Let’s have a look at the following example:
<?php class Student { private $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public function __destruct() { echo 'This will be called when the script is shut down...'; // save object state/other clean ups } } $objStudent = new Student('John', '[email protected]'); ?>
The __set()
Method
The __set()
magic method is called when you try to set data to inaccessible or non-existing object properties. The purpose of this method is to set extra object data for which you haven’t defined object properties explicitly.
Let’s get back to our example to understand how it works.
<?php class Student { private $data = array(); public function __set($name, $value) { $this->data[$name] = $value; } } $objStudent = new Student(); // __set() called $objStudent->phone = '0491 570 156'; ?>
As you can see in the above example, we’re trying to set the phone
property which is non-existent. And thus, the __set()
method is called. The first argument of the __set()
method is the name of the property which is being accessed and the second argument is the value we’re trying to set.
The __get()
Method
In the case of the __set()
method example in the previous section, we discussed how to set values for non-existent properties. The __get()
method is exactly the opposite of it. The __get()
magic method is called when you try to read data from inaccessible or non-existing object properties. The purpose of this method is to provide values to such properties.
Let’s see how it works in action.
<?php class Student { private $data = array(); public function __set($name, $value) { $this->data[$name] = $value; } public function __get($name) { If (isset($this->data[$name])) { return $this->data[$name]; } } } $objStudent = new Student(); // __set() called $objStudent->phone = '0491 570 156'; // __get() called echo $objStudent->phone; ?>
The __toString()
Method
The __toString()
magic method allows you to define what you would like to display when an object of the class is treated like a string. If you use echo
or print
on your object, and you haven’t defined the __toString()
method, it’ll give an error.
Let’s try to understand it with the following example.
<?php class Student { private $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public function __toString() { return 'Student name: '.$this->name . '<br>' . 'Student email: '.$this->email; } } $objStudent = new Student('John', '[email protected]'); echo $objStudent; ?>
In the above example, when you echo the $objStudent
object, it’ll call the __toString()
method. And in that method, you can decide what you would like to display. If you hadn’t defined the __toString()
method, this would have resulted in an error!
The __call()
and __callStatic()
Methods
If __get()
and __set()
methods are called when you’re dealing with non-existent properties, the __call()
method is called when you’re trying to invoke inaccessible methods, the methods that you haven’t defined in your class.
<?php class Student { public function __call($methodName, $arguments) { // $methodName = getStudentDetails // $arguments = array('1') } } $objStudent = new Student(); $objStudent->getStudentDetails(1); ?>
As you can see, we’ve called the method getStudentDetails
which is not defined, and thus the __call()
magic method is called. The first argument is the name of the method being called and the second argument is an array of arguments that were passed in that method.
The __callStatic()
method is very similar to the __call()
method with the only exception is that it’s called when you’re trying to invoke inaccessible methods in a static context. So if you’re trying to access any static method which is not defined, the __callStatic()
function will be called.
The __isset()
and __unset()
Methods
The __isset()
magic method is called when you call the isset()
method on inaccessible or non-existing object properties. Let’s see how it works through an example.
<?php class Student { private $data = array(); public function __isset($name) { return isset($this->data[$name]); } } $objStudent = new Student(); echo isset($objStudent->phone); ?>
In the above example, the phone property is not defined in the class, and thus it’ll call the __isset()
method.
On the other hand, the __unset()
is a method called when you call the unset()
method on inaccessible or non-existing object properties.
The __sleep()
and __wakeup()
Methods
The __sleep()
magic method is different compared to methods that we’ve discussed so far. It’s called when you call the serialize()
function on the object. In case of a very large object, you only want to save selected properties during serialization, and clean up the object. The __sleep()
method must return an array with the names of all properties of the object that should be serialized.
Again, let’s revise our example to see how it works.
<?php class Student { private $name; private $email; private $phone; private $db_connection_link; public function __construct($name, $email, $phone) { $this->name = $name; $this->email = $email; $this->phone = $phone; } public function __sleep() { return array('name', 'email', 'phone'); } public function __wakeup() { $this->db_connection_link = your_db_connection_function(); } } ?>
In the above example, when you serialize()
the Student
object, it’ll call the __sleep()
method and it’ll only preserve the values of name
, email
and phone
variables.
On the other hand, the use of the __wakeup()
magic method is to reestablish any connections and start up tasks when the unserialize()
function is called on the object.
The __invoke()
Method
The __invoke()
magic method is a special method which is called when you try to call an object as if it was a function. Firstly, let’s see how it works and then we’ll see the purpose of this magic method.
<?php class Student { private $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public function __invoke() { echo 'Student object is called as a function!'; } } $objStudent = new Student('John', '[email protected]'); $objStudent(); ?>
As you can see, the $objStudent
object is treated as if it was a function, and as we’ve defined the __invoke()
method, it’ll be called instead of giving you an error. The main purpose of the __invoke()
method is that if you want to treat your objects as callable, you can implement this method.
The __clone()
Method
If you want to duplicate an existing object, you could use the clone
keyword to do that. But after cloning, if you want to modify properties of the cloned object, you can define the __clone()
magic method in your class.
<?php Class Student_School { } class Student { private $name; private $email; private $object_student_school; public function __construct() { $this->object_student_school = new Student_School(); } public function __clone() { $this->object_student_school = clone $this->object_student_school; } } $objStudentOne = new Student(); $objStudentTwo = clone $objStudentOne; ?>
The issue with the above approach is that it makes a shallow copy of the object while cloning, and thus internal objects of the cloned object will not be cloned.
In the context of the above example, if you wouldn’t have defined the __clone()
method, the cloned object, $objStudentTwo
, would still point to the same Student_School
object referenced by the $objStudentOne
object. Thus, by implementing the __clone()
method, we make sure that the Student_School
object is cloned as well along with the main object.
The __debugInfo()
Method
The __debugInfo()
magic method is called when you try to dump any object by the var_dump()
function. If you haven’t defined this method in your class, it’ll dump all public, private and protected properties. So if you want to restrict the information which is displayed while dumping, you can use this method.
<?php class Student { public $name; private $email; private $ssn; public function __debugInfo() { return array('student_name' => $this->name); } } $objStudent = new Student(); var_dump($objStudent); // object(Student)#1 (1) { ["student_name"]=> NULL } ?>
This method should return an array of key, value pairs which will be displayed when the var_dump()
function is called on the object. As you can see, you can completely control what you want to display when the object will be dumped with the var_dump()
function.
The __set_state()
Method
The __set_state()
method is a static method which is used in conjunction with the var_export()
function. The var_export()
function outputs a structured information about a variable. When you use this function to export classes, you need to define the __set_state()
method in your class.
<?php class Student { public $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public static function __set_state(array $array) { $obj = new Student; $obj->name = $array['name']; $obj->email = $array['email']; return $obj; } } $objStudent = new Student('John','[email protected]'); var_export($objStudent); // Output: Student::__set_state(array( 'name' => 'John', 'email' => '[email protected]', )) ?>
As you can see, the exported string is a valid PHP code and you can use it to restore the original object.
Conclusion
In this article, we’ve gone through all the magic methods available in PHP. For every method, I provided a short but meaningful example which should help you to understand the purpose of it. And I hope you could use this article as a quick reference or a cheatsheet in your day-to-day PHP development.
The Best PHP Scripts on CodeCanyon
Explore thousands of the best and most useful PHP scripts ever created on CodeCanyon. With a low-cost one time payment, you can purchase these high-quality WordPress themes and improve your website experience for you and your visitors.
Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.