Deep Analysis and Implementation Methods for PHP Object to Array Conversion

Nov 16, 2025 · Programming · 10 views · 7.8

Keywords: PHP object conversion | get_object_vars | array processing | private properties | recursive conversion

Abstract: This article provides an in-depth exploration of various methods for converting objects to arrays in PHP, with a focus on the application scenarios of the get_object_vars() function when dealing with private properties. It also compares the advantages and disadvantages of alternative approaches such as type casting and JSON serialization, offering comprehensive technical references and practical guidance for developers through detailed code examples and performance analysis.

Core Concepts of Object to Array Conversion

In PHP development, the conversion between objects and arrays is a common programming requirement. Particularly when handling API responses, database query results, and similar scenarios, there is often a need to transform object structures into more manageable array formats. Based on technical analysis from highly-rated Stack Overflow answers, this article delves into the technical details of this conversion process.

Challenges in Accessing Private Properties

As evident from the provided example code, the original objects contain private properties _fields:private, which presents technical obstacles for direct access. In PHP, private properties can only be accessed within the class where they are defined, reflecting the encapsulation principle of object-oriented programming.

<?php
class Document {
    private $_fields = [];
    
    public function __construct($data) {
        $this->_fields = $data;
    }
    
    public function toArray() {
        return get_object_vars($this);
    }
}

// Usage example
$doc1 = new Document(['id' => 9093, 'name' => 'zahir']);
$doc2 = new Document(['id' => 9094, 'name' => 'hussain']);
$response = (object) [
    'response' => (object) [
        'docs' => [$doc1, $doc2]
    ]
];
?>

In-depth Analysis of get_object_vars() Function

As the recommended method in the best answer, the get_object_vars() function plays a crucial role in object conversion. This function returns an associative array of object properties, but its behavior is strictly constrained by property visibility.

<?php
// Calling get_object_vars() outside the class
$externalResult = get_object_vars($doc1);
print_r($externalResult);
// Output: Array() - because private properties are not visible

// Calling get_object_vars() inside the class
$internalResult = $doc1->toArray();
print_r($internalResult);
// Output: Array([_fields] => Array([id] => 9093 [name] => zahir))
?>

Comprehensive Conversion Solution

Addressing the nested object structure described in the original problem requires designing a recursive processing solution. The following implementation combines the core ideas from the best answer with functional extensions.

<?php
function convertObjectsToArray($data) {
    if (is_object($data)) {
        // If the object has a toArray method, use it preferentially
        if (method_exists($data, 'toArray')) {
            $data = $data->toArray();
        } else {
            // Get all properties in the object context
            $data = get_object_vars($data);
        }
    }
    
    if (is_array($data)) {
        // Recursively process array elements
        foreach ($data as $key => $value) {
            $data[$key] = convertObjectsToArray($value);
        }
    }
    
    return $data;
}

// Apply conversion
$resultArray = convertObjectsToArray($response->response->docs);
print_r($resultArray);
?>

Comparative Analysis of Alternative Methods

Beyond the get_object_vars() approach, PHP provides other object conversion techniques, each with specific application scenarios.

Type Casting Method

<?php
// Direct type casting
$arrayCast = (array) $doc1;
print_r($arrayCast);
// Output includes private properties, but property names are encoded
?>

JSON Serialization Method

<?php
// JSON serialization and deserialization
$jsonArray = json_decode(json_encode($response->response->docs), true);
print_r($jsonArray);
// Note: This method loses private property and method information
?>

Related Technology Comparison in JavaScript

Referencing the implementation concepts of Array.from(), we can draw inspiration from its design philosophy when handling iterable objects and array-like objects. Although PHP and JavaScript differ in language features, the core logic of data conversion shares common principles.

// JavaScript object conversion example
const obj = {0: {id: 9093, name: "zahir"}, 1: {id: 9094, name: "hussain"}};
const arr = Array.from(Object.values(obj));
console.log(arr);
// Output: [{id: 9093, name: "zahir"}, {id: 9094, name: "hussain"}]

Performance Optimization Considerations

When processing large-scale data, conversion performance becomes a critical factor. Based on actual testing, we observe the following performance characteristics:

Practical Application Scenarios

Object to array conversion is particularly important in the following scenarios:

Best Practice Recommendations

Based on technical analysis and practical experience, we recommend the following best practices:

  1. Preemptively consider conversion requirements in class design by implementing toArray() methods
  2. For objects containing private properties, perform conversion operations within the class
  3. Set depth limits when using recursive processing to prevent infinite recursion
  4. Consider using the __debugInfo() magic method to optimize debug output
  5. Avoid unnecessary conversion operations in performance-sensitive scenarios

Conclusion

Object to array conversion in PHP is a comprehensive technical issue involving language features, design patterns, and performance optimization. By deeply understanding the working principles of the get_object_vars() function and combining appropriate class design and conversion strategies, developers can efficiently handle various object conversion requirements. The solutions provided in this article not only address the technical challenges in the original problem but also offer reusable technical frameworks for similar development scenarios.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.