Home >Backend Development >PHP Problem >PHP object to array method

PHP object to array method

Guanhui
GuanhuiOriginal
2020-05-05 15:02:304645browse

PHP object to array method

PHP object to array method

The method of converting an object to an array in PHP can be achieved by using the "get_object_vars()" function , the syntax of this function is "get_object_vars($obj)", its parameter $obj represents the object that needs to be converted, and the return value of this function is an associative array composed of object attributes.

get_object_vars Description

get_object_vars ( object $obj ) : array


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 were not assigned a value, they would not be in the returned array. After PHP 4.2.0, these variables will be assigned NULL values ​​as key names.

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

?>


Print results:

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

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

The above is the detailed content of PHP object to array method. 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

Related articles

See more