Home > Article > Backend Development > How to convert object into array in php
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)".
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); ?>
Output:
Doing foo.Array ( )
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 )
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)); ?>
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 How to convert object into array in php. For more information, please follow other related articles on the PHP Chinese website!