How To Object To String In Php

In this blog post, we’ll learn how to convert an object to a string in PHP. This process, also known as serialization, can be useful in various situations, such as when you want to store an object’s state, send it as part of an API response, or display it for debugging purposes.

Using the __toString() Method

The most common way to convert an object to a string in PHP is by implementing the __toString() method in your class. The __toString() method is a magic method that gets called automatically when you try to use an object as a string.

Let’s look at an example. Suppose we have a simple class called Person:

        
class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}
        
    

To make this class convertible to a string, we’ll add the __toString() method, which will return a formatted string representing the object:

        
class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function __toString() {
        return "Name: {$this->name}, Age: {$this->age}";
    }
}
        
    

Now, we can easily convert a Person object to a string:

        
$person = new Person("John Doe", 30);
echo $person; // Output: Name: John Doe, Age: 30
        
    

Using serialize() and unserialize() Functions

If you need to store an object’s state and later recreate the object, you can use the serialize() and unserialize() functions. The serialize() function generates a storable representation of the object as a string, while the unserialize() function takes the serialized string and recreates the original object.

        
$person = new Person("Jane Doe", 28);
$serialized = serialize($person);
echo $serialized; // Output: O:5:"Person":2:{s:4:"name";s:7:"Jane Doe";s:3:"age";i:28;}

$unserialized = unserialize($serialized);
echo $unserialized; // Output: Name: Jane Doe, Age: 28
        
    

Note that using serialize() and unserialize() is not suitable for displaying human-readable strings, as the output format is meant for storing and recreating objects.

Conclusion

In this post, we’ve learned two ways to convert an object to a string in PHP. By implementing the __toString() method in your class, you can easily convert an object to a human-readable string. Alternatively, you can use the serialize() and unserialize() functions to store an object’s state and recreate it later. Choose the method that best fits your needs and happy coding!