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

php 对象如何变成数组

作者:凌傲天   发布日期:2024-03-03   浏览:1016

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

以下是一个示例:

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person = new Person("John", 25);
$array = get_object_vars($person);

print_r($array);

输出结果为:

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

另外,也可以将对象转换为数组使用 (array) 强制类型转换。但是需要注意的是,该方法只能转换对象的公有属性,私有属性和受保护属性无法被转换。

以下是使用强制类型转换的示例:

class Person {
    public $name;
    private $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person = new Person("John", 25);
$array = (array) $person;

print_r($array);

输出结果为:

Array
(
    [name] => John
    [Personage] => 25
)

注意到,私有属性 $age 被转换成了数组中的 Personage 键。

上一篇:php不同页面方法调用方法调用方法调用方法

下一篇:php 如何遍历数组的序号

大家都在看

php session用法

php 定义常量

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

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

Laravel 中文站