search
HomeBackend DevelopmentPHP ProblemHow to convert object into array in php

In PHP, we often use objects to express entities or concepts in reality, and arrays are also used to represent a set of related values ​​or data. For an already created object, we may need to convert it into an array to facilitate operations or transfer data. So, does PHP support converting objects into arrays?

The answer is yes. There are many ways to convert objects into arrays in PHP, including magic methods defined in classes, functions provided in the standard library, etc. Below we introduce the details of these methods respectively. implementation and use.

1. Use the magic method defined in the class

In PHP, we can realize the function of converting an object into an array by defining the magic method __toArray() in the class. The function of this method is The prototype is as follows:

public function __toArray(): array;

In the process of defining this method, we need to return an array with key-value pairs as elements, where the key is the attribute name and the value is the attribute value, for example:

class Person {
    private $name;
    private $age;
    
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
    
    public function __toArray(): array {
        return [
            'name' => $this->name,
            'age' => $this->age,
        ];
    }
}

$person = new Person('张三', 20);
$arr = $person->__toArray();
print_r($arr);

After running the above code, the output is as follows:

Array
(
    [name] => 张三
    [age] => 20
)

As you can see, by defining the __toArray() method, we successfully converted a Person object into an array.

2. Use standard library functions

In PHP, the standard library provides multiple functions to convert objects into arrays. Commonly used ones include get_object_vars(), json_decode(), etc. Below we Introduce the specific use of these functions.

  1. get_object_vars()

This function is used to obtain all attributes of an object (including private attributes), and returns an object with the attribute name as the key and the attribute value as the value. Array, for example:

class Person {
    private $name;
    private $age;
    
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person = new Person('张三', 20);
$arr = get_object_vars($person);
print_r($arr);

After running the above code, the output is as follows:

Array
(
    [name] => 张三
    [age] => 20
)

As you can see, even if the $name and $age attributes are both private attributes, you can still use the get_object_vars() method to which is successfully converted into an array.

  1. json_decode()

This function is used to decode a JSON string and convert it into a PHP variable, thereby converting an object into an array. For example:

class Person {
    private $name;
    private $age;
    
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person = new Person('张三', 20);
$json = json_encode($person);
$arr = json_decode($json, true);
print_r($arr);

After running the above code, the output is as follows:

Array
(
    [name] => 张三
    [age] => 20
)

As you can see, by converting the object into a JSON string and parsing it out using the json_decode() method, we have succeeded. Convert it into an array.

Summary

In PHP, we can use a variety of methods to convert an object into an array, including defining the __toArray() magic method in the class, using the standard library function get_object_vars(), json_decode() and other methods. Different methods are suitable for different occasions, and the specific use needs to be selected based on the actual situation.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.