php怎么把object转化成数组

php把object转化成数组的方法是:1、利用强制类型转换,在要转换的变量之前加上用括号括起来的目标类型“(array)”;2、使用“get_object_vars()”函数,返回由obj指定的对象中定义的属性组成的关联数组。

本教程操作环境:windows10系统、php8.1.3版本、DELL G3电脑。

php把object转化成数组的方法

方法1:利用强制类型转换–在要转换的变量之前加上用括号括起来的目标类型“(array)”

示例:object强制类型转换为array

1

2

3

4

5

6

7

8

9

10

11

class foo

{

function do_foo()

{

echo “Doing foo.”;

}

}

$bar = new foo;

$bar->do_foo();

print_r((array)$bar);

?>

登录后复制

输出:

1

Doing foo.Array ( )

登录后复制

扩展资料:

允许转换的PHP数据类型有:

(int)、(integer):转换成整形

(float)、(double)、(real):转换成浮点型

(string):转换成字符串

(bool)、(boolean):转换成布尔类型

(array):转换成数组

(object):转换成对象

方法2:使用get_object_vars()函数

get_object_vars — 返回由对象属性组成的关联数组。语法格式:

1

get_object_vars ( object $obj )

登录后复制

返回由 obj 指定的对象中定义的属性组成的关联数组。

示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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

?>

登录后复制

输出:

1

2

3

4

5

6

7

8

9

10

11

12

Array

(

[x] => 1.233

[y] => 3.445

[label] =>

)

Array

(

[x] => 1.233

[y] => 3.445

[label] => point #1

)

登录后复制

以上就是php怎么把object转化成数组的详细内容,更多请关注php中文网其它相关文章!

TG交流群(点击进入)----付费帮助搭建---修复---二开,以及发布求资源.
QQ交流群 922260178
© 版权声明
THE END
喜欢就支持一下吧
点赞2.6W+ 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容