Home >Backend Development >PHP Problem >How to convert objects into arrays in php
In PHP, Object and Array are two different data types. But sometimes we need to convert an object into an array, such as converting the properties and methods of a class instantiation object into an array for easy use.
In PHP, there are several ways to convert objects to arrays.
This is the most basic method and the simplest method. The get_object_vars() function can return an array of all attributes and attribute values in an object.
For example:
class MyClass { public $a = 1; protected $b = 2; private $c = 3; public function test(){ return "hello world!"; } } $obj = new MyClass(); $array = get_object_vars($obj); print_r($array);
Output:
Array ( [a] => 1 )
As you can see, the get_object_vars() function only obtains the value of the public attribute $a, while for the protected and private attributes $ b and $c, their values are not obtained.
In PHP, you can use type casting (Type Casting) to convert an object into an array. Forced type conversion uses the "(array)" keyword.
For example:
class MyClass { public $a = 1; protected $b = 2; private $c = 3; public function test(){ return "hello world!"; } } $obj = new MyClass(); $array = (array) $obj; print_r($array);
Output:
Array ( [a] => 1 [*b] => 2 MyClassprivatec] => 3 )
This array contains all properties and property values, but protected and private properties will be prefixed with a * or class name , distinguished from public properties.
It should be noted that this method does not list the methods in the object, only the properties of the object.
In PHP, you can use the json_decode() function to convert a JSON format string into an array or object. Therefore, an object's properties can be encoded in JSON format and then decoded into an array.
For example:
class MyClass { public $a = 1; protected $b = 2; private $c = 3; public function test(){ return "hello world!"; } } $obj = new MyClass(); $json = json_encode($obj); $array = json_decode($json, true); print_r($array);
Output:
Array ( [a] => 1 [b] => 2 [MyClassprivatec] => 3 )
It should be noted that this method will also convert protected and private properties into arrays, but will add the class name prefix.
The above are several methods of converting objects into arrays, including using the get_object_vars() function, forced type conversion and json_decode() function. The most commonly used ones are cast and json_decode() function.
It should be noted that when using forced type conversion and the json_decode() function, the values of protected and private attributes may be prefixed with class names or symbols such as *, which need to be processed according to specific circumstances.
The above is the detailed content of How to convert objects into arrays in php. For more information, please follow other related articles on the PHP Chinese website!