Sling Academy
Home/PHP/PHP: Convert a string into an object and vice versa

PHP: Convert a string into an object and vice versa

Last updated: January 10, 2024

Introduction

Manipulating data is a core aspect of any programming language. In PHP, developers often need to convert data between different types, such as turning a string representation of an object into an actual object, or serializing an object to a string. Such conversions are crucial for operations like storing objects in databases or sending them through APIs. This tutorial covers multiple approaches to convert strings to objects and vice versa in PHP.

Converting String to Object

To convert a string back into an object, PHP provides a few functions including unserialize() and json_decode(). Below we will explore these methods with examples.

Using unserialize()

The unserialize() function takes a single serialized string and converts it back to a PHP value.

Example:

<?php
$serializedObject = 'O:8:"stdClass":1:{s:5:"value";s:11:"Hello World";}';
$object = unserialize($serializedObject);
echo $object->value; // Outputs: Hello World
?>

Using json_decode()

For JSON strings, use json_decode(). It takes a JSON-encoded string and converts it into a PHP variable.

Example:

<?php
$jsonString = '{"value": "Hello World"}';
$object = json_decode($jsonString);
echo $object->value; // Outputs: Hello World
?>

Converting Object to String

Converting objects to strings is equally important and can be achieved through serialize() or json_encode(). Let’s dive into examples of each.

Using serialize()

This function returns a string containing a byte-stream representation of any value that can be stored in PHP.

Example:

<?php
$object = new stdClass();
$object->value = 'Hello World';
$serializedObject = serialize($object);
echo $serializedObject; // Outputs: O:8:"stdClass":1:{s:5:"value";s:11:"Hello World";}
?>

Using json_encode()

The json_encode() function returns the JSON representation of a value. It is useful when objects need to be passed to JavaScript or stored in a human-readable format.

Example:

<?php
$object = new stdClass();
$object->value = 'Hello World';
$jsonString = json_encode($object);
echo $jsonString; // Outputs: {"value":"Hello World"}
?>

Advanced Usage

PHP also allows for more complex operations such as defining __toString() method within classes for custom string representations, or using Serializable interface for advanced serialization possibilities.

Defining __toString() Method

A class can implement the magic method __toString() to control how it should behave when it is treated as a string.

Example:

<?php
class MyClass {
  public $value = 'Hello World';

  public function __toString() {
    return $this->value;
  }
}

$object = new MyClass();
echo $object; // Outputs: Hello World
?>

Implementing the Serializable Interface

For more control over serialization, PHP’s Serializable interface can be implemented. This allows you to define custom serialize() and unserialize() methods.

Example:

<?php
class MySerializableClass implements Serializable {
  private $value;

  public function __construct($value) {
    $this->value = $value;
  }

  public function serialize() {
    return serialize($this->value);
  }

  public function unserialize($data) {
    $this->value = unserialize($data);
  }

  public function getValue() {
    return $this->value;
  }
}

$myObject = new MySerializableClass('Hello World');
$serializedData = serialize($myObject);

$restoredObject = unserialize($serializedData);
echo $restoredObject->getValue(); // Outputs: Hello World
?>

Conclusion

Throughout this tutorial, we have seen that PHP provides various methods for converting objects to strings and strings to objects. Whether using the simple serialize() and unserialize(), or dealing with JSON data using json_encode() and json_decode(), PHP gives you the flexibility to handle object-string conversions proficiently. Remember that it’s essential to follow best practices for data security when using these functions, especially in dealing with user inputs or sensitive data.

Next Article: PHP: 2 ways to check if a string contains a number

Previous Article: PHP: Convert query string to an object and vice versa

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array