跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

php  对象怎么转数组

在 php 编程中,我们通常会使用对象来存储和处理数据。然而,在某些情况下,我们需要将对象转换为数组进行处理。 在 PHP 中,可以使用
get_object_vars()
函数将对象转换为数组。该函数带一个参数,即要转换为数组的对象。 下面是一个示例:
class Person { public $name = 'Tom'; public $age = 25; private $email = 'tom@email.com'; } $person = new Person(); $personArray = get_object_vars($person); print_r($personArray);
这个示例中,我们定义了一个名为
Person
的类,并在其中定义了三个属性:公有的
$name
$age
,以及私有的
$email
属性。然后,我们实例化了
Person
类,并将其传递给
get_object_vars()
函数以将其转换为数组。最后,我们将
personArray
数组打印输出。 输出结果如下: 立即学习 “ PHP免费学习笔记(深入) ”;
Array ( [name] => Tom [age] => 25 )
可以看出,只有公共属性被转换为数组,私有属性
$email
并没有被包含在数组中。 如果我们想包含私有属性,可以使用
ReflectionClass
类。该类允许我们访问和修改类的私有属性和方法。 下面是一个例子:
class Person { public $name = 'Tom'; public $age = 25; private $email = 'tom@email.com'; } $person = new Person(); $reflector = new ReflectionClass($person); $properties = $reflector->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE); $personArray = array(); foreach ($properties as $property) { $property->setAccessible(true); $personArray[$property->getName()] = $property->getValue($person); } print_r($personArray);
在这个示例中,我们使用了 ReflectionClass 类来获取类的信息。我们将
Person
类的实例传递给
ReflectionClass
构造函数,然后使用
getProperties()
方法获取类的属性,使用
ReflectionProperty::IS_PUBLIC
ReflectionProperty::IS_PRIVATE
参数来包含所有的公有属性和私有属性。接下来,我们使用
setAccessible()
方法将每个私有属性设置为可访问状态,并使用
getValue()
方法获取每个属性的值。最后,我们将这些属性和值存储在
$personArray
数组中,并打印输出。 输出结果如下: 立即学习 “ PHP免费学习笔记(深入) ”;
Array ( [name] => Tom [age] => 25 [email] => tom@email.com )
可以看出,包括私有属性
$email
在内的所有属性都被转换为了数组。 总结: 使用
get_object_vars()
函数可以将对象转换为数组,但只包含公共属性。如果需要包含私有属性,可以使用 ReflectionClass 类,并使用
setAccessible()
方法将私有属性设置为可访问状态,再使用
getValue()
方法获取私有属性的值。

相关文章