Home  >  Article  >  Backend Development  >  How to convert object array in php

How to convert object array in php

WBOY
WBOYOriginal
2023-05-19 21:48:36335browse

When programming in PHP, sometimes you need to convert objects into arrays. This operation can be achieved through a function, which is get_object_vars(), which can be used to convert an object into an array. Below we will introduce the usage of this function in detail and give an example of how to convert an object into an array.

get_object_vars() function

The get_object_vars() function can obtain all attributes and attribute values ​​of an object and return an associated array. The keys of this array are the attribute names and the values ​​are the attribute values. This function can only obtain the properties of the object, but cannot obtain the methods in the object. The following is the syntax of this function:

array get_object_vars (object $obj)

where $obj represents the object whose attributes are to be obtained. It returns an array containing the object's properties and values.

How to convert an object to an array

When converting an object to an array, you first need to create an object, and then call the get_object_vars() function to convert it into an array. Here is a sample code:

3a06b5f1b56d04ec2ed111bc767e90b6

In the above code, We first define a Person class, which has a public property $name, a private property $gender and a protected property $age. Then we create a $p object and convert it to an array. Finally, we use the print_r() function to output the array.

Run the above code, the output result is as follows:

Array
(

[name] => John
[gender:Person:private] => Male
[age:protected] => 20

)

As can be seen from the output result, the object $p The properties in have been successfully converted to arrays and can be accessed through arrays.

It should be noted that the get_object_vars() function can only obtain the attributes of the object, but cannot obtain the methods in the object. If you need to get the methods in the object, you need to use the getMethods() method of the ReflectionClass class to get all the methods in the object.

Summary

In PHP programming, converting an object into an array is a very basic operation. Here, we introduce how to use the get_object_vars() function to convert an object into an array, and explain the function in detail through sample code. If readers have other questions, it is recommended to refer to relevant PHP documents or other tutorials to learn.

The above is the detailed content of How to convert object array 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