php怎么将object转化为数组
时间:2021-06-18
来源:互联网
今天PHP爱好者给大家带来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);
?>
输出:
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));
?>
输出:
Array
(
[x] => 1.233
[y] => 3.445
[label] =>
)
Array
(
[x] => 1.233
[y] => 3.445
[label] => point #1
)
以上就是php怎么将object转化为数组的详细内容,更多请关注php爱好者其它相关文章!
-
明日方舟流行自选选哪个好-自选六星礼包干员推荐 时间:2025-05-10
-
燕云十六声新赛季战令值得买吗-新战令可以买吗 时间:2025-05-10
-
燕云十六声新赛季战令值得买吗-新战令可以买吗 时间:2025-05-10
-
bg交易所 时间:2025-05-10
-
王者荣耀QQ微信怎么组队-跨区组队排位方法 时间:2025-05-10
-
链上赚币赎回要多久才能到账?一般几天赎回来? 时间:2025-05-10
今日更新
-
php中$GLOBALS的用法是什么
阅读:18
-
php数组有哪几种类型
阅读:18
-
php 毫秒怎么转时间
阅读:18
-
什么是PHP中正则表达式的函数?(使用详解)
阅读:18
-
php7怎么开启错误提示
阅读:18
-
php中数组键值怎么进行转换
阅读:18
-
php怎么删除全部文件内容
阅读:18
-
javascript如何设置字体效果
阅读:18
-
浅谈使用Node.js搭建一个简单的 HTTP 服务器
阅读:18
-
php7 yaf扩展的安装方法
阅读:18