在 PHP 中,你可以通过多种方式将对象转换为数组。以下是几种常见的方法:
(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
)
注意:私有属性和受保护属性的键名会被修改,私有属性会在前面加上类名,受保护属性会在前面加上 *
。
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()
只会返回对象的公有属性。
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
)
注意:这种方法只会序列化对象的公有属性。
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
。根据你的需求选择合适的方法。