Home >Backend Development >PHP Problem >Is php object converted to array?
In PHP, we can convert objects into arrays by using some built-in functions. In this article, we will explore how to convert a PHP Object to an Array.
In PHP, we usually use objects to organize related properties and methods. In some cases, it may be more convenient to convert an object to an array because array operations can be more flexible. To achieve this purpose, PHP provides some built-in functions.
The following are some common methods of converting objects to arrays:
The get_object_vars function is used to obtain the attribute values of an object. , and returns an associative array. The parameter of this function is an object instance.
For example:
class Person { public $name; public $age; } $person = new Person(); $person->name = 'John'; $person->age = 30; $array = get_object_vars($person); print_r($array);
The above code will output:
Array ( [name] => John [age] => 30 )
json_decode and json_encode functions JSON strings can be converted into arrays and objects. We can convert PHP objects into JSON strings first, and then convert JSON strings into arrays.
For example:
class Person { public $name; public $age; } $person = new Person(); $person->name = 'John'; $person->age = 30; $json = json_encode($person); $array = json_decode($json, true); print_r($array);
The above code will output:
Array ( [name] => John [age] => 30 )
Using type conversion, you can Objects are converted directly to arrays. In PHP, when we cast an object to an array, the object's __toArray method is automatically called and an array is returned.
For example:
class Person { public $name; public $age; public function __toArray() { return [ 'name' => $this->name, 'age' => $this->age ]; } } $person = new Person(); $person->name = 'John'; $person->age = 30; $array = (array)$person; print_r($array);
The above code will output:
Array ( [name] => John [age] => 30 )
Summary
In PHP, converting an object to an array can be used for more flexibility to operate and process data. We can achieve this using get_object_vars function, json_decode and json_encode functions or type conversion. No matter which method is used, careful consideration is needed to ensure that the code is readable and maintainable.
The above is the detailed content of Is php object converted to array?. For more information, please follow other related articles on the PHP Chinese website!