PHP Magic Methods Cheatsheet

In this post, I’ll give you a cheatsheet 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 a 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. They also allow 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 each one briefly.

The __construct() 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:

In the above example, when you instantiate a new object with new student('John','john@tutsplus.com'), 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.

Keep in mind that the constructor of a parent class won’t be called implicitly if the child class has defined its own constructor.

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:

Just like constructors, a child can also inherit its parent’s destructor if it does not have its own implementation of one.

The __set() Method

The __set() magic method is called when you try to set data to inaccessible or non-existent 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.

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-existent object properties. The purpose of this method is to provide values to such properties.

Let’s see how it works in action.

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.

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

After reading about __get(), __set() and __call() methods, some of you be thinking about using them to manage all your class’s members and methods. Just try to avoid putting a lot of your code into them. It is usually better for readability and maintenance to have explicit method definitions for getting and setting members or defining class methods.

The __isset() and __unset() Methods

The __isset() magic method is called when you call the isset() method on inaccessible or non-existent object properties. Let’s see how it works through an example.

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-existent object properties.

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.

In the above example, when you echo the $objStudent object, it’ll call the __toString() method. 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 __sleep() and __wakeup() Methods

The __sleep() magic method is different compared to the methods that we’ve discussed so far. It’s called when you call the serialize() function on the object. In the 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.

In the above example, when you serialize() the Student object, it’ll call the __sleep() method, and it’ll only preserve the values of the name, email, and phone variables.

On the other hand, the use of the __wakeup() magic method is to re-establish any connections and start up tasks when the unserialize() function is called on the object.

The __serialize() and __unserialize() Methods

Two new magic methods called __serialize() and __unserialize() were introduced in PHP 7.4. In many ways, they are similar to the __sleep() and __wakeup() methods but they help us overcome some limitations of both these methods. For instance, creating a serialized representation of an object that is different from the in-memory form of the object would be difficult with __sleep() and require use of dummy properties.

It is also worth noting that only __serialize() is called when you have defined both __serialize() and __sleep() for an object. Similarly, only __unserialize() is called when you have defined both __unserialize() and __wakeup() for an 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 were a function. Firstly, let’s see how it works, and then we’ll see the purpose of this magic method.

As you can see, the $objStudent object is treated as if it were 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.

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 hadn’t 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 along with the main object.

The __debugInfo() Method

The __debugInfo() magic method is called when you try to dump an object using 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.

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 is 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 structured information about a variable. When you use this function to export classes, you need to define the __set_state() method in your class.

As you can see, the exported string is 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 can use this article as a quick reference or a cheatsheet in your day-to-day PHP development.

This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials, and to learn about new JavaScript libraries.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni

In this post, I'll give you a cheatsheet 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 a 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. They also allow 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 each one briefly.

The __construct() 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:

In the above example, when you instantiate a new object with new student('John','john@tutsplus.com'), 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.

Keep in mind that the constructor of a parent class won't be called implicitly if the child class has defined its own constructor.

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:

Just like constructors, a child can also inherit its parent's destructor if it does not have its own implementation of one.

The __set() Method

The __set() magic method is called when you try to set data to inaccessible or non-existent 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.

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-existent object properties. The purpose of this method is to provide values to such properties.

Let’s see how it works in action.

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.

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

After reading about __get(), __set() and __call() methods, some of you be thinking about using them to manage all your class's members and methods. Just try to avoid putting a lot of your code into them. It is usually better for readability and maintenance to have explicit method definitions for getting and setting members or defining class methods.

The __isset() and __unset() Methods

The __isset() magic method is called when you call the isset() method on inaccessible or non-existent object properties. Let’s see how it works through an example.

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-existent object properties.

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.

In the above example, when you echo the $objStudent object, it’ll call the __toString() method. 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 __sleep() and __wakeup() Methods

The __sleep() magic method is different compared to the methods that we’ve discussed so far. It’s called when you call the serialize() function on the object. In the 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.

In the above example, when you serialize() the Student object, it’ll call the __sleep() method, and it’ll only preserve the values of the name, email, and phone variables.

On the other hand, the use of the __wakeup() magic method is to re-establish any connections and start up tasks when the unserialize() function is called on the object.

The __serialize() and __unserialize() Methods

Two new magic methods called __serialize() and __unserialize() were introduced in PHP 7.4. In many ways, they are similar to the __sleep() and __wakeup() methods but they help us overcome some limitations of both these methods. For instance, creating a serialized representation of an object that is different from the in-memory form of the object would be difficult with __sleep() and require use of dummy properties.

It is also worth noting that only __serialize() is called when you have defined both __serialize() and __sleep() for an object. Similarly, only __unserialize() is called when you have defined both __unserialize() and __wakeup() for an 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 were a function. Firstly, let’s see how it works, and then we’ll see the purpose of this magic method.

As you can see, the $objStudent object is treated as if it were 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.

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 hadn’t 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 along with the main object.

The __debugInfo() Method

The __debugInfo() magic method is called when you try to dump an object using 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.

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 is 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 structured information about a variable. When you use this function to export classes, you need to define the __set_state() method in your class.

As you can see, the exported string is 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 can use this article as a quick reference or a cheatsheet in your day-to-day PHP development.

This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials, and to learn about new JavaScript libraries.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni


Print Share Comment Cite Upload Translate Updates
APA

Sajal Soni | Sciencx (2020-02-17T18:15:19+00:00) PHP Magic Methods Cheatsheet. Retrieved from https://www.scien.cx/2020/02/17/php-magic-methods-cheatsheet/

MLA
" » PHP Magic Methods Cheatsheet." Sajal Soni | Sciencx - Monday February 17, 2020, https://www.scien.cx/2020/02/17/php-magic-methods-cheatsheet/
HARVARD
Sajal Soni | Sciencx Monday February 17, 2020 » PHP Magic Methods Cheatsheet., viewed ,<https://www.scien.cx/2020/02/17/php-magic-methods-cheatsheet/>
VANCOUVER
Sajal Soni | Sciencx - » PHP Magic Methods Cheatsheet. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2020/02/17/php-magic-methods-cheatsheet/
CHICAGO
" » PHP Magic Methods Cheatsheet." Sajal Soni | Sciencx - Accessed . https://www.scien.cx/2020/02/17/php-magic-methods-cheatsheet/
IEEE
" » PHP Magic Methods Cheatsheet." Sajal Soni | Sciencx [Online]. Available: https://www.scien.cx/2020/02/17/php-magic-methods-cheatsheet/. [Accessed: ]
rf:citation
» PHP Magic Methods Cheatsheet | Sajal Soni | Sciencx | https://www.scien.cx/2020/02/17/php-magic-methods-cheatsheet/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.