Home > Backend Development > PHP Problem > How to convert object into array in php

How to convert object into array in php

zbt
Release: 2023-06-13 09:15:35
Original
2569 people have browsed it

The method for PHP to convert object into an array is: 1. Use forced type conversion and add the target type "(array)" enclosed in parentheses before the variable to be converted; 2. Use "get_object_vars( )" function, returns an associative array composed of attributes defined in the object specified by obj.

How to convert object into array in php

The operating environment of this tutorial: windows10 system, php8.1.3 version, DELL G3 computer.

php method to convert object into an array

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

Example: object cast to array

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): converted 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 an associative array composed of object attributes. 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:

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

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template