Home >Backend Development >PHP Tutorial >How to Convert stdClass Objects to Custom Classes in PHP?

How to Convert stdClass Objects to Custom Classes in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-26 09:15:111076browse

How to Convert stdClass Objects to Custom Classes in PHP?

Converting stdClass Objects to Custom Classes

In a scenario where a third-party storage system returns only stdClass objects, casting them into full-fledged objects of a specific class becomes necessary. However, PHP does not provide a straightforward casting method for such conversions.

Type Juggling

PHP's type juggling capabilities allow for specific conversions, such as:

  • (int) or (integer) for integer
  • (bool) or (boolean) for boolean
  • (float), (double), or (real) for float
  • (string) for string
  • (array) for array
  • (object) for object
  • (unset) for NULL (PHP 5)

These conversions are invaluable for working with stdClass objects, but they do not directly create instances of a specific class.

Custom Mapper

For comprehensive conversion, a Mapper class can be created to perform the casting from stdClass to a target class. This involves defining methods that translate each property of the stdClass object into the corresponding property in the target class.

Hackish Solution (Caution Advised)

As a workaround, the following code can be adapted to "pseudocast" arrays and objects to instances of a specific class:

function arrayToObject(array $array, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(serialize($array), ':')
    ));
}

function objectToObject($instance, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(strstr(serialize($instance), '"'), ':')
    ));
}

This solution modifies the serialized representation of the data to represent the target class. However, it is recommended to use this approach with caution due to potential side effects.

The above is the detailed content of How to Convert stdClass Objects to Custom Classes in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn