php将object转化为数组的方法:1、利用强制类型转换,语法“(array)Object变量”;2、利用get_object_vars()函数,语法“get_object_vars (object变量)”。

本教程操作环境:windows7系统、PHP7.1版,DELL G3电脑
方法1:利用强制类型转换--在要转换的变量之前加上用括号括起来的目标类型“(array)”
示例:object强制类型转换为array
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
print_r((array)$bar);
?>输出:
立即学习“PHP免费学习笔记(深入)”;
Doing foo.Array ( )
扩展资料:
允许转换的PHP数据类型有:
(int)、(integer):转换成整形
(float)、(double)、(real):转换成浮点型
(string):转换成字符串
(bool)、(boolean):转换成布尔类型
(array):转换成数组
(object):转换成对象
方法2:使用get_object_vars()函数
get_object_vars — 返回由对象属性组成的关联数组。语法格式:
get_object_vars ( object $obj )
返回由 obj 指定的对象中定义的属性组成的关联数组。
示例:
<?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));
?>输出:
立即学习“PHP免费学习笔记(深入)”;
Array
(
[x] => 1.233
[y] => 3.445
[label] =>
)
Array
(
[x] => 1.233
[y] => 3.445
[label] => point #1
)推荐学习:《PHP视频教程》
以上就是php怎么将object转化为数组的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号