How to convert object into array in php

青灯夜游
Release: 2023-03-10 13:16:01
Original
3940 people have browsed it

php method to convert object into an array: 1. Use forced type conversion, the syntax "(array)Object variable"; 2. Use the get_object_vars() function, the syntax "get_object_vars (object variable)".

How to convert object into array in php

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

Method 1: Use forced type conversion --Add the target type "(array)" enclosed in parentheses before the variable to be converted

Example: object cast to array

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo."; 
    }
}

$bar = new foo;
$bar->do_foo();
print_r((array)$bar);
?>
Copy after login

Output:

Doing foo.Array ( )
Copy after login

Extended information:

The PHP data types that allow conversion are:

  • (int), (integer): converted to Integer

  • (float), (double), (real): Convert to floating point type

  • (string): Convert to string

  • (bool), (boolean): Convert to Boolean type

  • (array): Convert to array

  • (object): Convert to object

Method 2: Use get_object_vars() function

get_object_vars - Returns the object properties An associative array composed of. Syntax format:

get_object_vars ( object $obj )
Copy after login

Returns an associative array composed of attributes 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));

?>
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 How to convert object into array in php. 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