Home  >  Article  >  Backend Development  >  What built-in function is used in php to convert an object into an array?

What built-in function is used in php to convert an object into an array?

青灯夜游
青灯夜游Original
2021-05-21 17:44:282288browse

In PHP, you can use the built-in function get_object_vars() to convert an object into an array. This function can return an associative array composed of object attributes, with the syntax format "get_object_vars(object)".

What built-in function is used in php to convert an object into an array?

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In PHP, you can use the built-in Function get_object_vars() to convert the object into an array

get_object_vars() returns an associative array composed of object attributes.

Syntax:

get_object_vars ( object $obj )

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

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));

?>

Output:

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

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

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What built-in function is used in php to convert an object into an array?. 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