Introduction to Magic Methods in PHP

Author - Webner
22.08.2018
|
0 Comments
||

Here we will go through different Magic Methods in PHP

The PHP functions which starts with the double underscore “__” are called magic methods. These are the methods which are always defined in classes, and can not be used alone i.e. outside the classes.

There are 15 types of magic methods that you can define in your classes. In fact, PHP only gives you magic names but does not provide any implementation of these methods. So, if we want to use magic methods outside any class, we have to implement that method, and then we can decide what our magic method will do. Here are some magic methods available to us from PHP.

1. __construct()
2. __destruct()
3. __call()
4. __callStatic()
5. __set()
6. __get()
7. __isset()
8. __unset()
9. __sleep()
10. __wakeup()
11. __toString()
12. __invoke()
13. __set_state()
14. __clone()
15. __debugInfo()

NOTE
We cannot directly call these magic methods like normal methods of a class. They are automatically triggered by PHP on different occasions.

For example
__construct method is automatically called when a new object is created.
__destruct method called before an object is deleted from the memory.
__sleep is called when an object is serialized.

Some important Examples

These are some examples for the better clarification about the usage and working of these magic methods.

1. __toString()

This magic method allows you to set a string value for the object that will be used if the object is needed to be converted into string. When we use echo on any object then this method is automatically called by PHP because it can read the object as string.

<?php
class Test
{
    public $name;
    public function __construct($name)
    {
        $this->name = $name;
    }
    public function __toString()
    {
        return "My name is " . $this->name;
        
    }
}
$obj = new Test('Gopi');
echo $obj;
?>

We have a class “Test” and it has one public property “name”. It also has a constructor which takes one argument and sets it as a value of the “name” property. Here we defined two string magic methods in this example. We are returning the string i.e “my name” and the value of the name property. Actually, this method should return any string value which you want to print. When someone uses your object and at last we are creating an object of our test class and passing it a string value “gopi” and then using echo on our object. Let’s see its result.

Output :

My name is Gopi

Now, what will happen if our class doesn’t have this magic method? Delete this (__toString()) magic method and let’s check the result again.

Output:-

Recoverable fatal error: Object of class Test could not be converted to string in C:\xampp\htdocs\magic\tostring.php on line 16

2. __invoke()

This magic method is automatically called when we use object of our class as a function.

<?php
Class test
{
}
$obj = new test;
$obj();
?>

Here, we have a class Test which doesn’t have any property or method defined in it and when we create an object of this class and then call this object as a function. Let’s see the result.

Fatal error:,/b. Uncaught Error: Function name must be a string in C:\xampp\htdocs\magic\invoke.php:6 Stack trace: #0 {main} thrown in C:\xampp\htdocs\magic\invoke.php on line 6

This happens because a function name must be a string. It means we cannot call our object as a function until we declare the __invoke magic method in our class.

<?php
class test
{
    public function __invoke()
    {
        echo "I can act as function no….";
    }
}
$obj = new test;
$obj();

?>

Now we have defined “__invoke()” magic method in our class. This method allows us to call our object as a function and it will print a message here whenever we call the object of this class as a function. Let’s see the result again.

Output

I can act as function now…

It means whenever we call our object as a function it automatically calls “__invoke()” magic method of our class.

Now, we can also check whether an object is callable or not using is_callable function. If it is callable, then it will return true otherwise false. Here is an example

<?php
class test
{
    public function __invoke()
    {
        echo "I can act as function no….";
    }
}
$obj = new test;
$obj();
var_dump(is_callable($obj)); //
?>

Output

I can act as function no….bool(true)

Now, if we delete this ” __invoke()” method and save the code. Let’s see what will be the result. If it’s false it means our test object is not valid to be called.

<?php
class test
{
}
$obj = new test;
var_dump(is_callable($obj));
?>

Output
bool(false)



3. __debugInfo() Magic Method

We should know why we need “__debugInfo()” method.

When we use “var_dump()” function on our object it dumps all the information about that object. All its public, protected and private properties and their values are shown. Now let’s take a look at this example.

<?php
Class Student
{
    Private $id;
    Public $name;
    Public function __construct($id, $name)
    {
        $this->id   = $id;
        $this->name = $name;
    }
}
$stuObj = new Student(2, ’’name”);
var_dump($stuObj);
?>

Output

object(Student)#1 (2) { [“id”:”Student”:private]=> int(2) [“name”]=> string(4) “name” }

If “__debugInfo()” method is defined then “var_dump()” will only show the info that debugInfo method is returning.

“var_dump()” method consider the object properties and their values as an array in the key value pair where properties name are the keys and their values are the values of those keys.

So the return value of “__debugInfo()” method should be an array of key value pair of properties that we want to expose when someone calls the “var_dump()” function on our object.

You can change property names and their values or you can simply say an array of key value pair. It may contain anything, not just the properties.

<?php
class Student
{
    private $id;
    public $name;
    public function __construct($id, $name)
    {
        $this->id   = $id;
        $this->name = $name;
    }
    public function __debugInfo()
    {
        return ['Student Id' => $this->id * 2, 'Address' => 'abc'];
    }
    
}
$stuObj = new Student(2, "name");
var_dump($stuObj);
?>

Here we have defined “__debugInfo()” magic method in our student class, which is returning an array of key value pair. It has only two elements, the key of the first one is “Student ID” and its value will be real ID multiplied by 2 and you can see that property is ID and here we are using a different name for this property student ID. The key of the second one is address and its value is “ABC” and you can see that address property doesn’t exist in our class so in “__debugInfo()” method you have to return an array of key value pair. It doesn’t matter what are the keys and what is their value, it should be an array of key value pair that’s it.

Output

object(Student)#1 (2) { [“Student Id”]=> int(4) [“Address”]=> string(3) “abc” }

Caution

PHP reserves all function names starting with “__”as magical. It is recommended that you do not define any function with the name starting with “__” in PHP unless you want some documented magic functionality of one of these magic methods.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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