get_object_vars() 返回对象在当前作用域可访问的非静态属性数组,仅限公共属性(外部调用时)或包含保护属性(内部调用时),不包括私有属性;与 (array) 转换不同,后者通过名称修饰包含所有属性,而递归转换、Reflection API 或 JsonSerializable 可处理嵌套对象或私有/保护属性,适用于复杂场景。

get_object_vars()
在PHP中,将对象转换为数组,
get_object_vars()
<?php
class User {
public $id = 1;
public $name = 'Alice';
protected $email = 'alice@example.com';
private $password = 'secret';
public function getEmail() {
return $this->email;
}
}
$user = new User();
$userData = get_object_vars($user);
print_r($userData);
/*
输出:
Array
(
[id] => 1
[name] => Alice
)
*/
// 如果我们在类内部调用 get_object_vars()
class Admin extends User {
public $role = 'admin';
public function getInternalVars() {
return get_object_vars($this);
}
}
$admin = new Admin();
$adminDataInternal = $admin->getInternalVars();
print_r($adminDataInternal);
/*
输出(在类内部,get_object_vars 可以访问所有可访问的属性,包括protected):
Array
(
[id] => 1
[name] => Alice
[email] => alice@example.com
[role] => admin
)
*/
?>从上面的例子可以看出,当
get_object_vars()
protected
然而,
get_object_vars()
Order
Customer
get_object_vars()
Order
Customer
立即学习“PHP免费学习笔记(深入)”;
get_object_vars()
(array)
说实话,这两种方式在 PHP 中都常被用来将对象“看起来”像数组,但它们底层的机制和结果却大相径庭,理解它们之间的差异对于避免一些奇怪的bug至关重要。我个人在初学PHP时,就曾因为混淆这两种方式而踩过坑。
get_object_vars()
而
(array)
我们来看个例子:
<?php
class Product {
public $name = 'Laptop';
protected $price = 1200;
private $sku = 'LAP-001';
}
$product = new Product();
echo "--- 使用 get_object_vars() ---\n";
print_r(get_object_vars($product));
/*
输出:
Array
(
[name] => Laptop
)
*/
echo "\n--- 使用 (array) 类型转换 ---\n";
print_r((array) $product);
/*
输出:
Array
(
[name] => Laptop
[*price] => 1200
[ Product sku] => LAP-001
)
*/
?>从输出你可以清晰地看到区别:
get_object_vars()
name
(array)
protected
price
*
private
sku
Product
所以,在我看来:
get_object_vars()
(array)
(array)
当
get_object_vars()
(array)
1. 针对私有/保护属性:利用 Reflection API
PHP的 Reflection API 是一个非常强大的工具,它允许你在运行时检查类、方法、属性等。通过 Reflection,你可以突破访问修饰符的限制,获取到对象的任何属性。
<?php
class Settings {
public $theme = 'dark';
protected $language = 'en';
private $adminEmail = 'admin@example.com';
}
function objectToArrayWithReflection($obj) {
$reflectionClass = new ReflectionClass($obj);
$properties = $reflectionClass->getProperties();
$array = [];
foreach ($properties as $property) {
$property->setAccessible(true); // 允许访问私有和保护属性
$array[$property->getName()] = $property->getValue($obj);
}
return $array;
}
$settings = new Settings();
$settingsArray = objectToArrayWithReflection($settings);
print_r($settingsArray);
/*
输出:
Array
(
[theme] => dark
[language] => en
[adminEmail] => admin@example.com
)
*/
?>这种方法非常强大,因为它能完全控制属性的访问。但它的缺点是性能开销相对较大,因为 Reflection 操作本身就比较“重”。所以,我通常只在需要深度内省或序列化整个对象(包括其私有状态)时才考虑它。
2. 针对嵌套对象:递归转换
这是最常见的场景之一。如果你有一个对象,它的某个属性值又是另一个对象,你需要将整个结构都转换为数组。这时候,一个递归函数就显得尤为重要。
<?php
class Address {
public $street = '123 Main St';
public $city = 'Anytown';
}
class Customer {
public $id = 101;
public $name = 'John Doe';
public $address; // 嵌套对象
private $secretKey = 'xyz'; // 私有属性
public function __construct() {
$this->address = new Address();
}
}
function convertObjectToArrayRecursive($obj) {
if (!is_object($obj) && !is_array($obj)) {
return $obj;
}
if (is_object($obj)) {
// 使用 get_object_vars() 获取公共属性
// 如果需要私有/保护属性,这里可以结合 Reflection API
$obj = get_object_vars($obj);
}
// 递归处理数组中的每个元素
return array_map(__FUNCTION__, $obj);
}
$customer = new Customer();
$customerArray = convertObjectToArrayRecursive($customer);
print_r($customerArray);
/*
输出:
Array
(
[id] => 101
[name] => John Doe
[address] => Array
(
[street] => 123 Main St
[city] => Anytown
)
)
*/
?>这个递归函数巧妙地利用了
get_object_vars()
array_map
convertObjectToArrayRecursive
get_object_vars()
get_object_vars($obj)
3. 利用 json_encode
json_decode
这是一种非常便捷,但也有其局限性的方法。
json_encode
json_decode
stdClass
<?php
class Article {
public $title = 'PHP Object to Array';
protected $author = 'Jane Doe';
private $views = 1000;
}
$article = new Article();
$jsonString = json_encode($article);
$articleArray = json_decode($jsonString, true); // true 表示返回关联数组
print_r($articleArray);
/*
输出:
Array
(
[title] => PHP Object to Array
)
*/
?>可以看到,
json_encode
JsonSerializable
jsonSerialize()
json_encode
<?php
class Author implements JsonSerializable {
public $name = 'Jane Doe';
private $email = 'jane@example.com';
public function jsonSerialize(): mixed {
return [
'name' => $this->name,
'email' => $this->email // 暴露私有属性
];
}
}
class Post implements JsonSerializable {
public $title = 'My Blog Post';
public $author; // 嵌套对象
protected $id = 1;
public function __construct() {
$this->author = new Author();
}
public function jsonSerialize(): mixed {
return [
'id' => $this->id, // 暴露保护属性
'title' => $this->title,
'author' => $this->author // 嵌套对象会自动调用其jsonSerialize
];
}
}
$post = new Post();
$postArray = json_decode(json_encode($post), true);
print_r($postArray);
/*
输出:
Array
(
[id] => 1
[title] => My Blog Post
[author] => Array
(
[name] => Jane Doe
[email] => jane@example.com
)
)
*/
?>这种方式在我看来,是处理复杂对象序列化到数组(尤其是用于API响应)最优雅且推荐的方式之一,因为它将序列化逻辑封装在对象自身中,符合面向对象的原则。
在我的开发生涯中,对象转数组这个操作,看似简单,实则暗藏玄机。踩过不少坑,也总结了一些经验。
常见的“坑”:
get_object_vars()
User
passwordHash
get_object_vars()
get_object_vars()
(array)
json_encode
json_encode
JsonSerializable
最佳实践:
JsonSerializable
jsonSerialize()
总的来说,对象转数组是一个非常实用的操作,但绝不是一个“一刀切”的问题。理解不同方法的优缺点,结合实际需求和场景,选择最合适的方案,才能写出健壮、高效且可维护的代码。
以上就是如何在PHP中将对象转为数组?get_object_vars()的正确用法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号