插件窝 干货文章 php 对象如何变成数组

php 对象如何变成数组

属性 array John 对象 153    来源:    2025-03-19

在 PHP 中,你可以通过多种方式将对象转换为数组。以下是几种常见的方法:

1. 使用 (array) 类型转换

你可以使用 (array) 将对象强制转换为数组。这种方法会将对象的属性转换为数组的键值对。

class MyClass {
    public $name = 'John';
    private $age = 30;
    protected $email = 'john@example.com';
}

$obj = new MyClass();
$array = (array) $obj;

print_r($array);

输出结果:

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

注意:私有属性和受保护属性的键名会被修改,私有属性会在前面加上类名,受保护属性会在前面加上 *

2. 使用 get_object_vars() 函数

get_object_vars() 函数可以获取对象的公有属性,并将其转换为数组。

class MyClass {
    public $name = 'John';
    private $age = 30;
    protected $email = 'john@example.com';
}

$obj = new MyClass();
$array = get_object_vars($obj);

print_r($array);

输出结果:

Array
(
    [name] => John
)

注意:get_object_vars() 只会返回对象的公有属性。

3. 使用 json_encode()json_decode()

你可以先将对象转换为 JSON 字符串,然后再将 JSON 字符串解码为数组。

class MyClass {
    public $name = 'John';
    private $age = 30;
    protected $email = 'john@example.com';
}

$obj = new MyClass();
$json = json_encode($obj);
$array = json_decode($json, true);

print_r($array);

输出结果:

Array
(
    [name] => John
)

注意:这种方法只会序列化对象的公有属性。

4. 使用 ReflectionClass

如果你需要获取对象的所有属性(包括私有和受保护的属性),可以使用 ReflectionClass

class MyClass {
    public $name = 'John';
    private $age = 30;
    protected $email = 'john@example.com';
}

$obj = new MyClass();
$reflection = new ReflectionClass($obj);
$properties = $reflection->getProperties();

$array = [];
foreach ($properties as $property) {
    $property->setAccessible(true);
    $array[$property->getName()] = $property->getValue($obj);
}

print_r($array);

输出结果:

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

注意:ReflectionClass 可以访问对象的私有和受保护属性,但需要调用 setAccessible(true) 来允许访问。

总结

  • 如果你只需要公有属性,可以使用 get_object_vars()json_encode()json_decode()
  • 如果你需要所有属性(包括私有和受保护的属性),可以使用 (array) 类型转换或 ReflectionClass

根据你的需求选择合适的方法。