Home > Backend Development > PHP Problem > What is the function to convert php object to array?

What is the function to convert php object to array?

青灯夜游
Release: 2023-03-10 12:46:01
Original
1439 people have browsed it

In PHP, the function to convert an object into an array is "get_object_vars()". The get_object_vars() function can return an associative array composed of object attributes, with the syntax format "get_object_vars (object)".

What is the function to convert php object to array?

The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer

In PHP, you can use the get_object_vars() function to convert the object into an array.

get_object_vars — Returns an associative array composed of object properties. Syntax format:

get_object_vars ( object $obj ) : array
Copy after login

Returns an associative array composed of attributes defined in the object specified by obj.

Note:

In versions prior to PHP 4.2.0, if variables declared in the obj object instance are not assigned a value, they will not be in the returned array . After PHP 4.2.0, these variables will be assigned null values ​​as key names.

Example:

<?php
class Point2D {
    var $x, $y;
    var $label;

    function Point2D($x, $y)
    {
        $this->x = $x;
        $this->y = $y;
    }

    function setLabel($label)
    {
        $this->label = $label;
    }

    function getPoint()
    {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "label" => $this->label);
    }
}

// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));

$p1->setLabel("point #1");
print_r(get_object_vars($p1));

?>
Copy after login

Output:

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] =>
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] => point #1
 )
Copy after login

Recommended learning: "PHP Video Tutorial

The above is the detailed content of What is the function to convert php object to array?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template