PHP Magic Methods Cheatsheet

In this post, I’ll give you a quick reference to all the magic methods available in PHP.

Whether you are an experienced PHP developer or a beginner in PHP development, if you have worked with OOP in PHP, you are already using at least a couple of magical PHP methods. However, if you haven’t heard of PHP magic methods yet, let me introduce you to them:

The names of the functions __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() And __debugInfo() they are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magical functionality associated with them. All magical methods MUST be declared public.

If you are wondering why these methods are called magic methods, it is because if you define one of these methods in your class, it will be called automatically and you should just define what should happen inside it. The best example of a magical 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 types of operations with objects. They also allow you to handle certain types of situations by manipulating objects.

PHP magic methods

The purpose of this article is to go through all the magic methods in PHP and explain them briefly.

The __construct() Method

If you define this method in your class, it will be called automatically when an object is instantiated. The purpose of this method is to assign some default values ​​to the properties of the object. This method is also called a builder.

Let’s take a look at a quick example to understand how this works:

In the example above, when you instantiate a new object with new student('John','john@tutsplus.com'), call the __construct() method first of all. In __construct() method, we assigned the values ​​passed in the arguments to the properties of the object.

Note that the constructor of a parent class will not be called implicitly if the child class has defined its own constructor.

The __destruct() Method

The __destruct() The method is called a destructor and is called when the object is destroyed. Typically, it is also called when the script is stopped or exited. The purpose of this method is to provide an opportunity to save the state of the object or any other cleanup you want to perform.

Let’s take a look at the following example:

Just like constructors, a child can also inherit its parent’s destructor if it doesn’t have its own implementation.

The __set() Method

The __set() The magic method is called when attempting to set data on inaccessible or non-existent object properties. The purpose of this method is to set additional object data for which object properties have not been explicitly defined.

Let’s go back to our example to understand how it works.

As you can see in the example above, we are trying to set the phone property, non-existent. And so, the __set() the method is called. The first argument of the __set() method is the name of the property being accessed and the second argument is the value we are trying to set.

The __get() Method

In the case of __set() method example in the previous section, we discussed how to set values ​​for nonexistent properties. The __get() method is exactly the opposite of it. The __get() The magic method is called when trying to read data from inaccessible or nonexistent object properties. The purpose of this method is to provide values ​​to these properties.

Let’s see how it works in action.

The __call() And __callStatic() methods

Self __get() And __set() methods are called when dealing with nonexistent properties, the __call() method is called when you are trying to invoke inaccessible methods, methods that you have not defined in your class.

As you can see, we have called the method getStudentDetails, which is not defined, and therefore the __call() it’s called the magic method. The first argument is the name of the called method and the second argument is an array of arguments passed into that method.

The __callStatic() the method is very similar to __call() method. The only exception is that it is called when trying to invoke inaccessible methods in a static context. So, if you are looking to access any static method that is not defined, the __callStatic() the function will be called.

After reading about __get(), __set() And __call() methods, some of you are thinking of using them to manage all the members and methods of your class. Just try to avoid putting a lot of code in them. It is usually best 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() the 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 example above, the phone property is not defined in the class and therefore will 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() The magic method allows you to define what you want to display when an object of the class is treated as a string. If you use echo or print on your object and you have not defined the __toString() method, it will give an error.

Let’s try to figure it out with the following example.

In the example above, when you echo a $objStudent object, it will call the __toString() method. In that method, you can decide what you want to view. If you hadn’t defined the __toString() method, this would have resulted in an error!

The __sleep() And __wakeup() methods

The __sleep() the magical method is different than the methods we have discussed so far. It is called when you call the serialize() function on the object. In the case of a very large object, you want to save only the properties selected during serialization and clean up the object. The __sleep() The method must return an array with the names of all properties of the object to be serialized.

Again, let’s review our example to see how this works.

In the example above, when you serialize() the Student object, it will call the __sleep() method and will 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 activities when the unserialize() the function is called on the object.

The __serialize() And __unserialize() methods

Two new magical methods called __serialize() And __unserialize() they 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 of these methods. For example, creating a serialized representation of an object that is different from the object’s in-memory shape would be difficult with __sleep() and require the use of fictitious properties.

It is also worth noting that only __serialize() is called when you have both defined __serialize() And __sleep() for an object. Likewise, only __unserialize() is called when you have both defined __unserialize() And __wakeup() for an object.

The __invoke() Method

The __invoke() The magic method is a special method that is called when trying to call an object as if it were a function. First, let’s see how it works, and then we’ll see the purpose of this magical method.

As you can see, the $objStudent the object is treated as if it were a function, and as we defined the __invoke() method, it will 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 can use the clone keyword to do it. But after cloning, if you want to change the properties of the cloned object, you can define the __clone() magic method in your class.

The problem with the above approach is that it creates a shallow copy of the object when cloning and then the internal objects of the cloned object will not be cloned.

In the context of the previous example, if you hadn’t defined the __clone() method, the cloned object, $objStudentTwo, would still indicate the same Student_School object referenced by the $objStudentOne object. So, by implementing the __clone() method, we make sure that the Student_School object is cloned together with the main object.

The __debugInfo() Method

The __debugInfo() the magic method is called when trying to unload an object using the var_dump() function. If you haven’t defined this method in your class, it will dump all public, private and protected properties. So, if you want to limit the information displayed during dump, you can use this method.

This method should return an array of key-value pairs that will be displayed when the var_dump() the function is called on the object. As you can see, you can fully control what you want to see when the object is downloaded with the var_dump() function.

The __set_state() Method

The __set_state() method is a static method that is used in conjunction with the var_export() function. The var_export() the function returns 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 have looked at all the magic methods available in PHP. For each method, I have provided a short but meaningful example that should help you understand its purpose. And I hope you can use this article as a quick reference or cheatsheet in your daily PHP development.

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

Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *