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