Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php怎么将对象转换为数组

作者:自然ㄣ之光   发布日期:2024-06-24   浏览:991

在PHP中,可以使用get_object_vars()函数将对象转换为数组。这个函数会返回一个包含对象属性和对应值的关联数组。

示例代码如下:

class Person {
    public $name;
    public $age;
}

$person = new Person();
$person->name = 'John';
$person->age = 30;

$array = get_object_vars($person);

print_r($array);

输出结果为:

Array
(
    [name] => John
    [age] => 30
)

除了使用get_object_vars()函数,还可以使用(array)强制类型转换来将对象转换为数组。但是需要注意的是,这种方法只能转换公共属性,私有属性和受保护属性无法转换。

示例代码如下:

class Person {
    public $name;
    protected $age;
    private $email;
}

$person = new Person();
$person->name = 'John';
$person->age = 30;
$person->email = 'john@example.com';

$array = (array)$person;

print_r($array);

输出结果为:

Array
(
    [name] => John
    [*age] => 30
    [Personemail] => john@example.com
)

在上面的输出结果中,[*age]表示$age属性是受保护的,[Personemail]表示$email属性是私有的。

上一篇:php扩展模块怎么安装

下一篇:php怎么将string类型转为int类型

大家都在看

php session用法

php 定义常量

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站