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:
class Person{
public $name; private $gender; protected $age; public function __construct($n,$g,$a){ $this->name = $n; $this->gender = $g; $this->age = $a; }
}
$p = new Person('John',' Male',20);
$array = get_object_vars($p);
print_r($array);
?>
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!